出于测试目的,我需要在数百个电子邮箱中填充各种消息,为此我将使用smtplib。但在其他事情中,我需要能够发送消息不仅到特定的邮箱,但抄送和密件他们以及。在发送电子邮件时, smtplib 看起来不支持抄送和密送。
寻找建议如何做抄送或密件抄送发送来自python脚本的消息。
(而且-不,我不会创建一个脚本来向我的测试环境之外的任何人发送垃圾邮件。)
发布于 2009-10-09 22:52:29
电子邮件头对smtp服务器无关紧要。当您发送电子邮件时,只需将抄送和密件抄送收件人添加到toaddr。对于CC,将它们添加到CC头部。
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\r\n" % fromaddr
+ "To: %s\r\n" % toaddr
+ "CC: %s\r\n" % ",".join(cc)
+ "Subject: %s\r\n" % message_subject
+ "\r\n"
+ 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()
发布于 2015-04-29 14:57:03
关键的事情是将收件人添加为sendmail呼叫中的电子邮件in列表。
import smtplib
from email.mime.multipart import MIMEMultipart
me = "user63503@gmail.com"
to = "someone@gmail.com"
cc = "anotherperson@gmail.com,someone@yahoo.com"
bcc = "bccperson1@gmail.com,bccperson2@yahoo.com"
rcpt = cc.split(",") + bcc.split(",") + [to]
msg = MIMEMultipart('alternative')
msg['Subject'] = "my subject"
msg['To'] = to
msg['Cc'] = cc
msg.attach(my_msg_body)
server = smtplib.SMTP("localhost") # or your smtp server
server.sendmail(me, rcpt, msg.as_string())
server.quit()
发布于 2019-05-31 01:33:58
从2011年11月发布的Python3.2开始,smtplib有了一个新的函数send_message
,而不仅仅是sendmail
,这使得处理To/CC/BCC变得更容易。从Python official email examples中提取,经过一些微小的修改,我们得到:
# Import smtplib for the actual sending function
import smtplib
# Import the email modules we'll need
from email.message import EmailMessage
# Open the plain text file whose name is in textfile for reading.
with open(textfile) as fp:
# Create a text/plain message
msg = EmailMessage()
msg.set_content(fp.read())
# me == the sender's email address
# you == the recipient's email address
# them == the cc's email address
# they == the bcc's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you
msg['Cc'] = them
msg['Bcc'] = they
# Send the message via our own SMTP server.
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()
使用头部可以很好地工作,因为send_message respects BCC as outlined in the documentation
send_message不会传输消息中可能出现的任何密件抄送或重新发送-密件抄送标头
使用sendmail
时,通常会将CC标头添加到消息中,如下所示:
msg['Bcc'] = blind.email@adrress.com
或
msg = "From: from.email@address.com" +
"To: to.email@adress.com" +
"BCC: hidden.email@address.com" +
"Subject: You've got mail!" +
"This is the message body"
问题是,sendmail函数对所有这些头文件都一视同仁,这意味着它们将被(可见地)发送给所有的To:和BCC: users,这违背了BCC的目的。正如这里的许多其他答案所示,解决方案是不在邮件头中包含密件抄送,而是仅在传递给sendmail
的电子邮件列表中包含密件抄送。
需要注意的是,send_message
需要一个消息对象,这意味着您需要从email.message
导入一个类,而不仅仅是将字符串传递到sendmail
中。
https://stackoverflow.com/questions/1546367
复制相似问题