Joel G Mathew
Joel G Mathew

Reputation: 8061

Send email with sender and recipient header in python

After failing to send email with Mailgun API, I have been sending email with SMTP successfully using smtplib, with the following code.

def send_simple_message(mailtext, mailhtml):
    print("Mailhtml is:" + mailhtml)
    logging.basicConfig(level=logging.DEBUG)
    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    msg = MIMEMultipart('alternative')
    msg['Subject'] = "Summary of Credit Card payments due"
    msg['From']    = "[email protected]"
    msg['To']      = "[email protected]"
    s = smtplib.SMTP('smtp.mailgun.org', 587)
    part1 = MIMEText(mailtext, 'plain')
    part2 = MIMEText(mailhtml, 'html')
    msg.attach(part1)
    msg.attach(part2)
    s.login('[email protected]', 'password')
    s.sendmail(msg['From'], msg['To'], msg.as_string())
    s.quit()

However this displays the sender field as [email protected]. How can I add a sender header field so the sender is shown as Someone important ([email protected]) instead?

Upvotes: 2

Views: 5114

Answers (1)

Joel G Mathew
Joel G Mathew

Reputation: 8061

I solved it by using Header from email.header and formataddr from email.utils. My complete working script looks like this:

def send_simple_message(mailtext, mailhtml, month, files=None):
    # print("file is:" + filename)
    logging.basicConfig(level=logging.DEBUG)
    import smtplib
    from os.path import basename
    from email.mime.application import MIMEApplication
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    from email.header import Header
    from email.utils import formataddr
    Recipient = "[email protected]"
    msg = MIMEMultipart('alternative')
    msg['Subject'] = "Summary of Credit Card payments due in " + month
    msg['From'] = formataddr((str(Header('Finance Manager', 'utf-8')), '[email protected]'))
    msg['To']      = Recipient
    part1 = MIMEText(mailtext, 'plain')
    part2 = MIMEText(mailhtml, 'html')
    msg.attach(part1)
    msg.attach(part2)
    for f in files or []:
        with open(f, "rb") as fil:
            part = MIMEApplication(
                fil.read(),
                Name=basename(f)
            )
        # After the file is closed
        part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
        msg.attach(part)

    s = smtplib.SMTP('smtp.mailgun.org', 587)
    s.login('[email protected]', 'pass')
    s.sendmail(msg['From'], msg['To'], msg.as_string())
    s.quit() 

Upvotes: 4

Related Questions