Save email as .eml file with python - python

I am trying to export an Email message obtained with aiosmtpd to an *.eml file that I can later open with any *.eml viewer or email client like Thunderbird or Mail.
async def handle_DATA(self, server, session, envelope) -> str:
msg: EmailMessage = message_from_bytes(envelope.content, policy=policy.SMTPUTF8)
with open("test.eml", 'wb') as outfile:
outfile.write(msg.as_bytes())
I've also tried to save the file with Generator with both unixfrom=False and unixfrom=False and same thing.
with open("test.eml", 'w') as file:
emlGenerator = generator.Generator(file)
emlGenerator.flatten(msg, unixfrom=False)
The file gets created correctly but not all the eml files can be read correctly by Mail or Thunderbird.
Emails received from gmail.com are created correctly but emails received from protonmail.com are not. Eml files created from Protonmail emails can be opened but only from and to parameters of the email can be seen. I can't see the content neither the attachments in it.
I guess it does not have the format that eml parsers are expecting to see.
I've tried with different policies (like policy.SMTP, policy.default, ...).
What is the proper way to create eml files with python?
NOTE: The content of the EML file for Protonmail contains the following This is an OpenPGP/MIME signed message (RFC 4880 and 3156). Could this be related with the lack of correct parsing for Protonmail emails?

I had the same issue with the Email API. Although it can not always be opened directly as an .eml file, it is correctly opened if the message is sent to an SMTP server. I understand the Email API generates a string that represents the data sent to the SMTP server. That data is to be interpreted by an SMTP server, not a client. The SMTP server will interpret this data and store it as if finds more convenient (i.e. storing it in a db).
A client like Thunderbird will retrieve the message using POP3 or IMAP, but that doesn't mean that it is retrieving the same message that was sent to the SMTP server, since the server might store it in a different format.

Related

Create a file that will automatically send an e-mail when clicked on?

My program takes entered data and creates several batch / docx files. Is there a way to take my entered data and create a file that, when clicked on, will automatically send an e-mail to a specified e-mail address from a specific Gmail account? or better yet, open chrome and prepare the e-mail to be sent text and all?
The Gmail account I would like to use is delegated (controlled by various users), and the e-mail would have to come from this account, and not my personal Gmail account that I'm signed in to as well.
edit: it doesn't have to open chrome. can be anything. as long as i can make changes before i hit send.
Create a batch file that will run a python file that you create
For example a batch file with the following line
python -m your_module.your_python_file
create a python file called your_python_file.py with the following code
import logging
from logging.handlers import SMTPHandler
if(__name__ == "__main__"):
logger = logging.getLogger()
server_email_address = 'your_gmail_address'
server_account_password = 'your_gmail_password'
destination_email_address = 'destination_email_address'
emailh = SMTPHandler(('smtp.gmail.com', 587)
,server_email_address
,destination_email_address
,'your subject'
,(server_email_address, server_account_password)
, secure=())
emailh.setLevel(logging.WARNING)
logger.addHandler(emailh)
# input the email message to send
msg = input('enter message \n')
# send the email
logger.warning(msg)
when you click on the batch file, it should open a console window and run the python code. It should prompt you for an input - the email message to be sent - then it will send the email

IMAP with python to download attachments

I have a instrument at work that emails me a file containing raw data, I can go into my email and download them easily enough but when I have multiple files (which it sends as multiple emails) it gets a bit tedious.
I'm looking at using python and imaplib to login to my email account, search for emails from a known email address within the past day or so and then download any attachments to a directory. So I thought a script might help here.
I've setup a gmail account and altered the settings so that I can connect using imap from a shell, however I'm lost as to where to go from here.
Could someone point me in the right direction as to what I need to do to make this happen.
Here is a repository that is forked off imaplib (made compatible with Python3.6, did not test other versions)
https://github.com/christianwengert/mail
The following snippet checks all unseen messages, then returns their attachments:
server = IMAPClient(imap, use_uid=True, ssl=993)
server.login(username, password)
server.select_folder('INBOX')
message_ids = server.search([b'NOT', b'SEEN']) # UNSEEN
messages = server.fetch(message_ids, data=['ENVELOPE', 'BODYSTRUCTURE', 'RFC822.SIZE'])
for mid, content in messages.items():
bodystructure = content[b'BODYSTRUCTURE']
text, attachments = walk_parts(bodystructure, msgid=mid, server=server)
HTH

How to send mail to selected mailbox on Gmail?

I want to send mail into selected mailbox(mail folder, Gmail's label) on a gmail account.
Actually, I made a function which is getting emails on selected mailbox through IMAP Protocol. But, now I have to make a function which sends emails into my selected mailbox.
How can i selectively send mail to this mailbox?

Sending email from a Django app hosted on Heroku with attachment stored in AWS S3

So I want to send an email from Django/Python hosted with Heroku with an attachment (PDF) located in an S3 bucket. So I can send an email with a file attachment that is locally stored but I can't find a way to attach a remotely hosted file to an email.
As an additional point, I'm trying to use Mandrill but this isn't the main requirement.
I'm simply trying to send an email from python/django with an attachment without having to save the attachment locally first (as this isn't recommended/possible/ideal with my Heroku setup)
This is simple enough, assuming your file is stored as a normal file field (with a different storage selected), then you can do the following:
message = EmailMessage(subject, body, from_email, bcc=recipient_list)
message.attach(FILENAME, mymodel.myfilefield.read())
This will just download the file from S3 temporarily into the memory and send the email with the attachment without the necessity to use the local filesystem.

Attachment Sent to Kindle From Google Appengine not being Recognized

Using the code below I am trying to send an attachment to my Kindle from an Appengine App.
from google.appengine.api import mail
import cStringIO
out=cStringIO.StringIO()
out.write('Hello, World!')
reading = mail.EmailMessage(
sender='[sender email]',
subject='convert',
to=[list or recipient emails],
attachments=[('test.txt', out.getvalue())])
reading.send()
However, Amazon replies with
Your email to Kindle(s) did not include any attachments
Next I tried adding my email to the list of recipients and I get the email with the attachment just fine.
How come Amazon doesn't?
You're trying to send a .TXT file, but that's not a supported file type.
From Amazon's documentation:
Kindle Personal Documents Service supports multiple file types, including:
Microsoft Word (.DOC, .DOCX)
HTML (.HTML, .HTM)
RTF (.RTF)
JPEG (.JPEG, .JPG)
Kindle Format (.MOBI, .AZW)
GIF (.GIF)
PNG (.PNG)
BMP (.BMP)
PDF (.PDF)

Categories