我正在尝试使用以下代码从 iCloud 电子邮件地址发送一些电子邮件:
import smtplib
def main():
smtp_obj = smtplib.SMTP('smtp.mail.me.com', 587)
smtp_obj.starttls()
smtp_obj.login('[email protected]', 'password')
pairs = {'name_1': '[email protected]', 'name_2': '[email protected]'}
try:
for name in pairs.keys():
body = 'hi {}'.format(name)
print('Sending email to {}...'.format(name))
send_status = smtp_obj.sendmail(smtp_obj.user, pairs.get(name), body)
if send_status != {}:
print('There was a problem sending mail to {}.\n{}'.format(name, send_status))
except smtplib.SMTPDataError:
print('Sending email to {} failed.'.format(name))
finally:
smtp_obj.quit()
if __name__ == '__main__':
main()
但是,当我运行这个时,我只得到一个 SMTPDataError,说,
smtplib.SMTPDataError: (550, b'5.7.0 From address is not one of your addresses')
我尝试过对不同的地址进行硬编码。当我使用我的地址时,我得到了这个。当我使用一个我知道错误的地址时,错误消息还会打印出无效的电子邮件(该帐户无法访问该电子邮件 - 例如,列出未登录的 Gmail 地址以查看会发生什么情况)。
有人知道这是怎么回事吗?
谢谢!
我解决了这个问题。事实证明,“发件人”和“收件人”地址必须作为消息正文的一部分提供,icloud 才能发送电子邮件。
我缺少的代码段如下:
try:
for name in pairs.keys():
msg = ('From: {}\r\nTo: {}\r\n\r\nHi, {}'.format(smtp_obj.user,
pairs.get(name),
name))
print('Sending email to {} at {}...'.format(name, pairs.get(name)))
send_status = smtp_obj.sendmail(from_addr=smtp_obj.user,
to_addrs=pairs.get(name),
msg=msg)
if send_status != {}:
print('There was a problem sending mail to {}.\n{}'.format(name, send_status))
finally:
smtp_obj.quit()
email
模块 更容易构建具有正确标头的电子邮件,从而避免了问题。
import email.message
import smtplib
smtp = smtplib.SMTP('smtp.mail.me.com', 587)
smtp.starttls()
smtp.login('[email protected]', 'mypassword')
message = email.message.EmailMessage()
message.set_content('Hello, world!')
message['Subject'] = 'Test message'
message['From'] = '[email protected]'
message['To'] = '[email protected]'
try:
errs = smtp.send_message(message)
if errs:
raise smtplib.SMTPException(f'Failures: {errs}')
finally:
smtp.quit()