我有一个 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()