Python 电子邮件未发送到密件抄送



我正在尝试制作一些可以发送电子邮件的python代码。到目前为止,我已经成功了,但密件抄送没有收到消息。

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

上面的代码假定您的输入字符串不包含逗号,除非作为分隔符。 原则上,诸如"To:"之类的标头可以包含实名部分,这些部分可以包含逗号,例如:

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

如果可以使用此方法,则另一种方法是列出任何不为空的To/CC/BCC标头,并将它们连接在","上,这样您就不必拆分任何字符串:

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: %srn" % sender + "To: %srn" % reciever + "CC: %srn" % ",".join(cc) + "Subject: %srn" % subject + "rn"  + 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!")

相关内容

  • 没有找到相关文章

最新更新