以下是2个代码块。第一个将向gmail发送一条消息,其中包含正确的主题和发件人。但是,当我将第一个代码放入函数时,电子邮件会丢失发件人和主题信息。
为什么会这样,我该如何解决?
我希望能够从其他python脚本调用此函数,以便在我的工作完成时通知我。该功能无误地运行和运行,电子邮件将其发送到我的收件箱,但我丢失了发件人信息,更重要的是,主题标题。
按预期运行的第一个代码:
import smtplib
gmail_user = 'name@domain.com'
gmail_password = 'password'
sent_from = gmail_user
to = ['recipient@domain.com']
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()
丢失主题和发件人信息的第二个代码:
def mailer(subject, body):
import smtplib
gmail_user = 'name@domain.com'
gmail_password = 'password'
sent_from = gmail_user
to = ['recipient@domain.com']
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)
答案 0 :(得分:1)
这很可能是一个行结束问题。每个邮件头都需要以CRLF(\r\n
)结尾。原始消息字符串可能包含正确的结尾(在编辑器中不可见),这些结尾随后在复制/粘贴到功能版本期间丢失。为了确保每一行都正确结束,请尝试将每个行表示为单独的字符串,并将其与\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
])