我有一个python脚本通过下面显示的Gmail SMTP设置发送电子邮件,工作正常。但是,当我尝试将其转换为函数时,它不再发送任何电子邮件。你能给我的任何帮助都将不胜感激。
import smtplib
SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587
sender = 'account@gmail.com'
password = 'password'
recipient = ['user@Email1.com', 'user@Email2.com']
subject = 'Gmail SMTP Test'
body = 'blah blah blah'
body = "" + body + ""
headers = ["From: " + sender,
"Subject: " + subject,
"To: " + ", " .join(recipient),
"MIME-Version: 1.0",
"Content-Type: text/html"]
headers = "\r\n".join(headers)
session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
session.ehlo()
session.starttls()
session.ehlo
session.login(sender, password)
session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
session.quit()
如果我尝试将其包装成一个函数,它就不再发送电子邮件了。我已经在def SendEmail()上尝试了几个不同的变量而没有运气。
import smtplib
def SendEmail(self):
SMTP_SERVER = 'account.gmail.com'
SMTP_PORT = 587
sender = 'account@gmail.com'
password = 'Password'
recipient = ['user@Email1.com', 'user@Email2.com']
subject = 'Gmail SMTP Test'
body = 'blah blah blah'
body = "" + body + ""
headers = ["From: " + sender,
"Subject: " + subject,
"To: " + ", " .join(recipient),
"MIME-Version: 1.0",
"Content-Type: text/html"]
headers = "\r\n".join(headers)
session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
session.ehlo()
session.starttls()
session.ehlo
session.login(sender, password)
session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
session.quit()
答案 0 :(得分:4)
您忘了拨打电话。另外,您不需要self
参数:
import smtplib
def SendEmail():
SMTP_SERVER = 'account.gmail.com'
SMTP_PORT = 587
sender = 'account@gmail.com'
password = 'Password'
recipient = ['user@Email1.com', 'user@Email2.com']
subject = 'Gmail SMTP Test'
body = 'blah blah blah'
body = "" + body + ""
headers = ["From: " + sender,
"Subject: " + subject,
"To: " + ", " .join(recipient),
"MIME-Version: 1.0",
"Content-Type: text/html"]
headers = "\r\n".join(headers)
session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
session.ehlo()
session.starttls()
session.ehlo
session.login(sender, password)
session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
session.quit()
SendEmail()
此外,将SMTP_SERVER
中的常量移动到单独的配置文件中或者移动到函数外部可能是个好主意。另外,如果您将recipient
,subject
,body
变量作为函数参数传递而不是在函数内部对它们进行硬编码,那么它看起来会更好。
此外,此session.ehlo
(无括号)行不执行任何操作。