Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating and saving an .eml file with python 3.3

I am trying to generate emails using the standard email library and save them as .eml files. I must not be understanding how email.generator works because I keep getting the error 'AttributeError: 'str' object has no 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?

like image 694
user3434523 Avatar asked May 23 '14 19:05

user3434523


People also ask

How do I save an EML file?

Go to File (or Menu icon) > Save as > File (this gives you the full content of the message including the message headers). Enter a name or leave the default option in place. Click Save and your message will be saved in a file with a . eml extension.

How do I save an email thread as EML?

Double-click and open the email message that you want to save in . eml format. Click the File tab and then click Save As. Click on the arrow down button in the Where field and browse to the file location where you want save the file.


1 Answers

Here is a modified solution that works with extra headers too. (This was tested with 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 ============"
like image 99
Ajay Gautam Avatar answered Oct 18 '22 20:10

Ajay Gautam