Lisle
Lisle

Reputation: 1690

Using function to send gmails via python

Below are 2 code blocks. The first will send a message to gmail with the correct subject and sender. However, when I put the first code into a function, the email loses the sender and subject info.

Why is this and how do I fix it?

I would like to be able to call this function from other python scripts to notify me when my job is complete. The function works and runs without error, and the email makes it to my inbox, but I lose the sender info and more importantly, the subject heading.

1st code that runs as expected:

import smtplib

gmail_user = '[email protected]'  
gmail_password = 'password'

sent_from = gmail_user
to = ['[email protected]'] 
subject = "job complete" 
body = "python script " + str(name) + " has finished"

email_text = """\
From: %s  
To: %s  
Subject: %s

%s
""" % (sent_from, ", ".join(to), subject, body)

server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(gmail_user, gmail_password)
server.sendmail(sent_from, to, email_text)
server.close()

2nd code that loses subject and sender info:

def mailer(subject, body):
    import smtplib

    gmail_user = '[email protected]'  
    gmail_password = 'password'

    sent_from = gmail_user
    to = ['[email protected]'] 
    subject = subject 
    body = body

    email_text = """\
    From: %s  
    To: %s  
    Subject: %s

    %s
    """ % (sent_from, ", ".join(to), subject, body)

    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    server.ehlo()
    server.login(gmail_user, gmail_password)
    server.sendmail(sent_from, to, email_text)
    server.close()

subject = "job complete"
body = "python script " + str(name) + " has finished"

mailer(subject, body)

Upvotes: 0

Views: 89

Answers (1)

Nikolas Stevenson-Molnar
Nikolas Stevenson-Molnar

Reputation: 4710

It's most likely a line ending issue. Each mail headers is required to end with CRLF (\r\n). The original message string may have contained the correct endings (invisible in the editor) which were subsequently lost during copy/paste to the function version. To ensure that each line is ended correctly, try expressing each as a separate string and joining them with \r\n.

email_text = '\r\n'.join([
    'From: %s' % sent_from,
    'To: %s' % ', '.join(to),
    'Subject: %s' % subject',
    '',  # Blank line to signal end of headers
    body
])

Upvotes: 1

Related Questions