Python 电子邮件未发送到 BCC

Python Emails Not Sending to BCC

我正在尝试编写一些 python 代码来发送电子邮件。到目前为止我已经成功了,但是 BCC 没有收到消息。

"""
June 18, 2020

@author: Carlos
"""
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
mail = smtplib.SMTP("smtp.gmail.com", 587)
msg = MIMEMultipart()

message = input("Your message: ")
password = input("Your password: ")
msg['From'] = input("Your email: ")
msg['To'] = input("Reciever(s): ")
msg['CC'] = ", " + input("CC(s): ")
msg['BCC'] = ", " + input("BCC(s): ")
msg['Subject'] = input("Your header: ")

msg.attach(MIMEText(message, 'plain'))

mail.ehlo()

mail.starttls()

mail.login(msg['From'], password)

mail.sendmail(msg['From'], msg['To'] + msg['CC'] + msg['BCC'], msg.as_string())

mail.close()

print("Successfully sent email to %s:" % (msg['To']))

您可能不希望密件抄送成为邮件本身的一部分(因为根据定义它不应该被收件人看到),因此最好将它存储在一个单独的变量中而不是作为一个元素MIMEMultipart 个实例。

您也不希望将前导逗号等(添加只是为了帮助连接字符串)放入 msg 的元素中,因为它们将构成消息的一部分。

如果你这样做:

msg['To'] = input("Receiver(s): ")
msg['CC'] = input("CC(s): ")
bcc = input("BCC(s): ")

然后您可以使用以下方法构造所有收件人的列表:

all_recipients = sum([s.split(",") for s in (msg['To'], msg['CC'], bcc) if s],
                     [])

然后您可以使用以下方式发送消息:

mail.sendmail(msg['From'], ",".join(all_recipients), msg.as_string())

以上代码假定您的输入字符串不包含逗号(逗号除外)作为分隔符。原则上 header 如 "To:" 可以包含实名部分,这些部分可以包含逗号,例如:

"John Doe, Yoyodyne, Inc." <john.doe@yoyodyne.example.com>

如果可以使用,那么另一种方法是制作一个 To/CC/BCC header 不为空的列表,并加入 "," 上的列表,这样您不必拆分任何字符串:

non_empty_recipient_headers = [h for h in (msg['To'], msg['CC'], bcc) if h]

mail.sendmail(msg['From'], ",".join(non_empty_recipient_headers), msg.as_string())

我找到了无法发送的问题的解决方案!如果有人感兴趣,这是我的代码!

"""
June 20, 2020

@author: Carlos
"""
import smtplib
mail = smtplib.SMTP("smtp.gmail.com", 587)

sender = input("Your email: ")
password = input("Your password: ")
reciever = input("Receiver(s): ")
cc = [input("CC(s): ")]
bcc = [input("BCC(s): ")]
subject = input("Your header: ")
message_text = input("Your message: ")
message = "From: %s\r\n" % sender + "To: %s\r\n" % reciever + "CC: %s\r\n" % ",".join(cc) + "Subject: %s\r\n" % subject + "\r\n"  + message_text
to = [reciever] + cc + bcc

mail.ehlo()

mail.starttls()

mail.login(sender, password)

mail.sendmail(sender, to, message)

mail.close()

print("Successfully sent email!")