python:如何使用TO、CC和BCC发送邮件?

问题描述:

出于测试目的,我需要用各种消息填充数百个电子邮件框,并打算为此使用 smtplib.但除此之外,我不仅需要能够向特定邮箱发送消息,还需要能够向它们发送 CC 和 BCC.它看起来不像 smtplib 在发送电子邮件时支持 CC-ing 和 BCC-ing.

I need for testing purposes to populate few hundred email boxes with various messages, and was going to use smtplib for that. But among other things I need to be able to send messages not only TO specific mailboxes, but CC and BCC them as well. It does not look like smtplib supports CC-ing and BCC-ing while sending emails.

寻求建议如何从 python 脚本执行 CC 或 BCC 发送消息.

Looking for suggestions how to do CC or BCC sending messages from the python script.

(而且——不,我不会创建一个脚本来向我的测试环境之外的任何人发送垃圾邮件.)

(And — no, I'm not creating a script to spam anyone outside of my testing environment.)

电子邮件标头与 smtp 服务器无关.只需在发送电子邮件时将 CC 和 BCC 收件人添加到 toaddrs 中即可.对于 CC,请将它们添加到 CC 标头中.

Email headers don't matter to the smtp server. Just add the CC and BCC recipients to the toaddrs when you send your email. For CC, add them to the CC header.

toaddr = 'buffy@sunnydale.k12.ca.us'
cc = ['alexander@sunydale.k12.ca.us','willow@sunnydale.k12.ca.us']
bcc = ['chairman@slayerscouncil.uk']
fromaddr = 'giles@sunnydale.k12.ca.us'
message_subject = "disturbance in sector 7"
message_text = "Three are dead in an attack in the sewers below sector 7."
message = "From: %s
" % fromaddr
        + "To: %s
" % toaddr
        + "CC: %s
" % ",".join(cc)
        + "Subject: %s
" % message_subject
        + "
" 
        + message_text
toaddrs = [toaddr] + cc + bcc
server = smtplib.SMTP('smtp.sunnydale.k12.ca.us')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, message)
server.quit()