Creating and saving .eml file with python 3.3

I am trying to create emails using a standard electronic library and save them as .eml files. I should not understand how email.generator works, because I keep getting the error. AttributeError: 'str' object does not have the attribute 'write.'

from email import generator
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
active_dir = 'c:\\'

class Gen_Emails(object):
    def __init__(self):
        self.EmailGen()

    def EmailGen(self):
        sender = 'sender'
        recepiant = 'recipiant'
        subject = 'subject'

        msg = MIMEMultipart('alternative')
        msg['Subject'] = subject
        msg['From'] = sender
        msg['To'] = recepiant


        html = """\
        <html>
            <head></head>
            <body>
                <p> hello world </p>
            </body>
        </html>
        """
        part = MIMEText(html, 'html')

        msg.attach(part)

        self.SaveToFile(msg)

    def SaveToFile(self,msg):
        out_file = active_dir
        gen = generator.Generator(out_file)
        gen.flatten(msg)

Any ideas?

+4
source share
2 answers

It is supposed to transfer the open file (in recording mode) to Generator(). Currently, you only pass a string to it, so it fails when it tries to call .write()in a string.

So do something like this:

import os
cwd = os.getcwd()
outfile_name = os.path.join(cwd, 'message.eml')

class Gen_Emails(object):    

    # ...

    def SaveToFile(self,msg):
        with open(outfile_name, 'w') as outfile:
            gen = generator.Generator(outfile)
            gen.flatten(msg)

: with open(outfile_name, 'w') as outfile outfile_name outfile. with.

os.path.join() -plattform , .

os.getcwd() . , , .

+4

, . ( Python 2.6)

import os
from email import generator
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

html_data = ...

msg = MIMEMultipart('alternative')
msg['Subject'] = ...
msg['From'] = ...
msg['To'] = ...
msg['Cc'] = ...
msg['Bcc'] = ...
headers = ... dict of header key / value pairs ...
for key in headers:
    value = headers[key]
    if value and not isinstance(value, basestring):
        value = str(value)
    msg[key] = value

part = MIMEText(html_data, 'html')
msg.attach(part)

outfile_name = os.path.join("/", "temp", "email_sample.eml")
with open(outfile_name, 'w') as outfile:
    gen = generator.Generator(outfile)
    gen.flatten(msg)

print "=========== DONE ============"
+2

Source: https://habr.com/ru/post/1541823/


All Articles