我想尝试用python发送电子邮件,并找到了一些在线的barebone代码
import smtplib
gmail_user = 'myaddress@gmail.com'
gmail_pw = 'myPassword'
sent_from = gmail_user
to = ['mailAdrr1@domain.com', 'mailAdrr2@domain.com']
subject = 'Some Subject'
body = 'Some body'
email_text = """
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
try:
smtp_server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
smtp_server.ehlo()
smtp_server.login(gmail_user, gmail_pw)
smtp_server.sendmail(sent_from, to, email_text)
smtp_server.close()
print("Success")
except Exception as ex:
print("Error: ", ex)
现在我想分别向每个目标发送电子邮件,所以我在代码中添加了一个foreach循环。这导致电子邮件头被弄乱,所有的头都被解释为来自头。虽然当我把它们打印出来时,它们看起来很好
在对为什么会发生这种情况感到非常困惑之后,我决定尝试将整个代码包装在for循环中,并进行一次迭代,根据我的理解,这应该不会改变任何东西。但事实上,它确实产生了与上述相同的问题。以下是我将代码包装在循环中的方式:
import smtplib
for i in range(1):
gmail_user = 'myaddress@gmail.com'
gmail_pw = 'myPassword'
sent_from = gmail_user
to = ['mailAdrr1@domain.com', 'mailAdrr2@domain.com']
subject = 'Some Subject'
body = 'Some body'
email_text = """
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
try:
smtp_server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
smtp_server.ehlo()
smtp_server.login(gmail_user, gmail_pw)
smtp_server.sendmail(sent_from, to, email_text)
smtp_server.close()
print("Success")
except Exception as ex:
print("Error: ", ex)
为什么只有一次迭代的for循环会改变代码的工作方式?
我猜这是你想要的代码:
import smtplib
gmail_user = 'MyEmail@gmail.com'
gmail_pw = 'MyPassword'
sent_from = gmail_user
to = ['PersonA@gmail.com', 'PersonB@gmail.com']
subject = 'Some Subject for multiple people'
body = 'Some body for a few'
smtp_server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
smtp_server.ehlo()
smtp_server.login(gmail_user, gmail_pw)
for email in to:
email_text = 'Subject:{}nn{}'.format(subject, body)
try:
smtp_server.sendmail(sent_from, email, email_text)
print("Success")
except Exception as ex:
print("Error: ", ex)
smtp_server.close()
你处理它的方式有两个主要问题。无论出于何种原因,如果您在循环中登录,它就会失败。我把它移到开头,并在末尾调用close(),以防止多次登录。第二个问题与如何格式化电子邮件数据本身有关。我用了这个回答的例子来帮助你完成这个工作,所以更多的内容请参阅:如何在用gmail发送的电子邮件中添加主题?
希望,这解决了您的问题!非常感谢,GhostDog