问题:Python:如何使用TO,CC和BCC发送邮件?

为了进行测试,我需要在数百个电子邮件框中填充各种消息,并打算为此使用smtplib。但是除其他外,我不仅需要能够向特定邮箱发送消息,还需要向它们发送CC和BCC消息。看起来smtplib在发送电子邮件时不支持CC-ing和BCC-ing。

寻找有关如何执行CC或BCC从python脚本发送消息的建议。

(而且-不,我不是在创建脚本向测试环境之外的任何人发送垃圾邮件。)

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.

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.)


回答 0

电子邮件标头与smtp服务器无关。发送电子邮件时,只需将抄送和密件抄送收件人添加到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()

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\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()

回答 1

关键是将收件人添加为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.attach(my_msg_body)
server = smtplib.SMTP("localhost") # or your smtp server
server.sendmail(me, rcpt, msg.as_string())
server.quit()

Key thing is to add the recipients as a list of email ids in your sendmail call.

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()

回答 2

不要添加密件抄送头。

看到这个: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()

Don’t add the bcc header.

See this: http://mail.python.org/pipermail/email-sig/2004-September/000151.html

And this: “””Notice that the second argument to sendmail(), the recipients, is passed as a list. You can include any number of addresses in the list to have the message delivered to each of them in turn. Since the envelope information is separate from the message headers, you can even BCC someone by including them in the method argument but not in the message header.””” from 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()

回答 3

从2011年11月发布的Python 3.2开始,smtplib具有一个新功能,send_message而不是just sendmail,这使得处理To / CC / BCC更加容易。从Python官方电子邮件示例提取一些修改后,我们得到:

# 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遵循文档中概述的BCC

send_message不传输可能在味精中显示的任何密件抄送或Resent-Bcc标头


随着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:用户,这违背了BCC的目的。如此处其他许多答案所示,解决方案是在标题中不包含密件抄送,而仅在传递给的电子邮件列表中包含BCC sendmail

需要注意的是,它send_message需要一个Message对象,这意味着您需要从中导入一个类,email.message而不仅仅是将字符串传递到中sendmail

As of Python 3.2, released Nov 2011, the smtplib has a new function send_message instead of just sendmail, which makes dealing with To/CC/BCC easier. Pulling from the Python official email examples, with some slight modifications, we get:

# 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()

Using the headers work fine, because send_message respects BCC as outlined in the documentation:

send_message does not transmit any Bcc or Resent-Bcc headers that may appear in msg


With sendmail it was common to add the CC headers to the message, doing something such as:

msg['Bcc'] = blind.email@adrress.com

Or

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"

The problem is, the sendmail function treats all those headers the same, meaning they’ll get sent (visibly) to all To: and BCC: users, defeating the purposes of BCC. The solution, as shown in many of the other answers here, was to not include BCC in the headers, and instead only in the list of emails passed to sendmail.

The caveat is that send_message requires a Message object, meaning you’ll need to import a class from email.message instead of merely passing strings into sendmail.


回答 4

TO,CC和BCC之间的区别仅出现在文本标题中。在SMTP级别,每个人都是收件人。

收件人-收件人地址为“收件人:”标题

抄送-有此收件人地址的抄送:标头

密件抄送-根本没有在标题中提到此收件人,但仍然是收件人。

如果你有

TO: abc@company.com
CC: xyz@company.com
BCC: boss@company.com

您有三个收件人。电子邮件正文中的标题将仅包含TO:和CC:

The distinction between TO, CC and BCC occurs only in the text headers. At the SMTP level, everybody is a recipient.

TO – There is a TO: header with this recipient’s address

CC – There is a CC: header with this recipient’s address

BCC – This recipient isn’t mentioned in the headers at all, but is still a recipient.

If you have

TO: abc@company.com
CC: xyz@company.com
BCC: boss@company.com

You have three recipients. The headers in the email body will include only the TO: and CC:


回答 5

您可以尝试MIMEText

msg = MIMEText('text')
msg['to'] = 
msg['cc'] = 

然后发送msg.as_string()

https://docs.python.org/3.6/library/email.examples.html

You can try MIMEText

msg = MIMEText('text')
msg['to'] = 
msg['cc'] = 

then send msg.as_string()

https://docs.python.org/3.6/library/email.examples.html


回答 6

在我创建之前,它对我不起作用:

#created cc string
cc = ""someone@domain.com;
#added cc to header
msg['Cc'] = cc

并且在收件人[列表]中添加了抄送,例如:

s.sendmail(me, [you,cc], msg.as_string())

It did not worked for me until i created:

#created cc string
cc = ""someone@domain.com;
#added cc to header
msg['Cc'] = cc

and than added cc in recipient [list] like:

s.sendmail(me, [you,cc], msg.as_string())

回答 7

由于我在“收件人”和“抄送”中都有多个收件人,因此上述所有内容都不适合我。所以我尝试如下:

recipients = ['abc@gmail.com', 'xyz@gmail.com']
cc_recipients = ['lmn@gmail.com', 'pqr@gmail.com']
MESSAGE['To'] = ", ".join(recipients)
MESSAGE['Cc'] = ", ".join(cc_recipients)

并使用“ cc_recipients”扩展“收件人”并以平凡的方式发送邮件

recipients.extend(cc_recipients)
server.sendmail(FROM,recipients,MESSAGE.as_string())

None of the above things worked for me as I had multiple recipients both in ‘to’ and ‘cc’. So I tried like below:

recipients = ['abc@gmail.com', 'xyz@gmail.com']
cc_recipients = ['lmn@gmail.com', 'pqr@gmail.com']
MESSAGE['To'] = ", ".join(recipients)
MESSAGE['Cc'] = ", ".join(cc_recipients)

and extend the ‘recipients’ with ‘cc_recipients’ and send mail in trivial way

recipients.extend(cc_recipients)
server.sendmail(FROM,recipients,MESSAGE.as_string())

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。