python:如何用TO,CC和BCC发送邮件?
我需要testing的目的,填充几百个电子邮件框与各种消息,并打算使用smtplib的。 但除此之外,我需要能够发送消息不仅要特定的邮箱,但CC和密件抄送它们以及。 它看起来不像smtplib在发送电子邮件时支持CC-ing和BCC-ing。
寻找build议如何从Python脚本中执行CC或BCC发送消息。
(而且 – 不,我不是创build一个脚本垃圾邮件在我的testing环境以外的任何人。)
电子邮件标题与smtp服务器无关。 当您发送电子邮件时,只需将CC和BCC收件人添加到toaddrs。 对于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()
你可以试试MIMEText
msg = MIMEText('text') msg['to'] = msg['cc'] =
然后发送msg.as_string()
TO,CC和BCC之间的区别仅在文本标题中出现。 在SMTP级别,每个人都是收件人。
TO – 这个收件人的地址有一个TO:标题
CC – 这个收件人的地址有一个CC:标头
BCC – 收件人根本没有在标题中提及,但仍是收件人。
如果你有
TO: abc@company.com CC: xyz@company.com BCC: boss@company.com
你有三个收件人。 电子邮件正文中的标题将只包含TO:和CC:
不要添encryption件抄送标题。
看到这个: http : //mail.python.org/pipermail/email-sig/2004-September/000151.html
而且这个:“”“请注意sendmail()的第二个参数是收件人,作为一个列表传递,你可以在列表中包含任意数量的地址,依次将消息传递给每个地址,信息与信息标题是分开的,甚至可以通过将它们包含在方法参数中,而不是在信息标题中对某人进行BCC。“”“来自http://pymotw.com/2/smtplib
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) # don't add this, otherwise "to and cc" receivers will know who are the bcc receivers # + "BCC: %s\r\n" % ",".join(bcc) + "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()
关键是将收件人添加为sendmail调用中的电子邮件ID列表 。
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['Bcc'] = bcc msg.attach(my_msg_body) server = smtplib.SMTP("localhost") # or your smtp server server.sendmail(me, rcpt, msg.as_string()) server.quit()
它没有为我工作,直到我创build:
#created cc string cc = ""someone@domain.com; #added cc to header msg['Cc'] = cc
而不是在收件人列表中添加cc:
s.sendmail(me, [you,cc], msg.as_string())