Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a properly formatted email using Python and SMTP?

Tags:

python

email

smtp

I am trying to send an email using Python script but somehow in the format I am expecting the email to come in my mailbox, it is not coming in that format. Below is my method which is sending an email -

def send_mail(data):
    sender = '[email protected]'
    receivers = ['[email protected]']

    message = """From: [email protected]
    To: [email protected]
    Subject: Send mail from python!!

    """
    body = 'Some Text\n'
    for item in data:
        body = body + '{name} - {res}\n'.format(name=item['name'], res=item['res'])

    message = message + body

    try:
       smtpObj = smtplib.SMTP('corp.host.com' )
       smtpObj.sendmail(sender, receivers, message)
       print "Mail sent"
    except smtplib.SMTPException:
       print "You can't spam. Mail sending failed!"

Here data just have key - value pair.

And I am getting an email like this in my Outlook mailbox -

In the From: section in my outlook, below string is coming as it is which is wrong -

[email protected] To: [email protected] Subject: Send mail from python!!

And To: , Subject: section is coming as Empty which is also wrong.

And in the body I am seeing everything coming in a single line but I want the result to be shown as -

Some Text

machinA - 0
machineB - 0
machineC - 0

How can I represent my data to be shown like this in my Outlook mailbox?

like image 896
AKIWEB Avatar asked May 24 '26 13:05

AKIWEB


1 Answers

Since triple quoting preserves all spaces, you were accidentally sending:

From: [email protected]
      To: [email protected]
      Subject: Send mail from python!!

This invokes header unfolding: indented lines mean that the header is continued. So this really is a badly formatted From header. You need to make sure there are no extraneous spaces. This fixes up your current example:

def send_mail(data):
    sender = '[email protected]'
    receivers = ['[email protected]']

    message = """\
From: [email protected]
To: [email protected]
Subject: Send mail from python!!
"""
    body = '\n\nSome Text\n'
    for item in data:
        body = body + '{name} - {res}\n'.format(name=item['name'], res=item['res'])

    message = message + body

    try:
       smtpObj = smtplib.SMTP('corp.host.com' )
       smtpObj.sendmail(sender, receivers, message)
       print "Mail sent"
    except smtplib.SMTPException:
       print "You can't spam. Mail sending failed!"

However, you shouldn't be manually constructing messages at all. Python includes an assortment of lovely classes in email.message for constructing a message.

import email.message

m = email.message.Message()
m['From'] = "[email protected]"
m['To'] = "[email protected]"
m['Subject'] = "Send mail from python!!"

m.set_payload("Your text only body");

Now, you can turn your message into a string:

>>> m.as_string()
'To: [email protected]\nFrom: [email protected]\nSubject: Send mail from python!!\n\nyour text-only body'

I will warn you, properly dealing with email is a very large and complex topic, and if you want to use non-ascii, attachments, etc, there's a bit of a learning curve, and you will need to use all the faculties of the email.message library, which has a lot of documentation you should read and understand.

like image 60
Max Avatar answered May 26 '26 03:05

Max



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!