繁体   English   中英

发送带有python中多个地址附件的电子邮件

[英]Send an email having an attachment for multiple addresses in python

我编写了下面的代码,用于向多个地址发送电子邮件。...但是我只能将列表中的第一个地址发送给邮件...可以为我提供确切的原因和解决方案。 提前致谢!!

from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from smtplib import SMTP
COMMASPACE = ', '

msg = MIMEMultipart()
msg['Subject'] = 'Test attaching mail'
msg['From'] = 'x@x.com'
msg['Reply-to'] = ''
msg['To'] = COMMASPACE.join(['x1@x.com','x2@x.com','x3@x.com'])

# That is what u see if dont have an email reader:
msg.preamble = 'Multipart massage.\n'

# This is the textual part:
part = MIMEText("Hello im sending an email from a python program")
msg.attach(part)

# This is the binary part(The Attachment):
file="../logs_usecase/TestUsecase.log"
part = MIMEApplication(open(file,"rb").read())
part.add_header('Content-Disposition', 'attachment', filename=file)
msg.attach(part)

# Create an instance in SMTP server
smtp = SMTP("smtp.gmail.com:587")
# Start the server:
smtp.starttls()
smtp.ehlo()
smtp.login('x@x.com', "xxxxx")

# Send the email
smtp.sendmail(msg['From'], msg['To'], msg.as_string())

SMTP.sendmail需要一个收件人列表 ,但是您要传递带有串联电子邮件地址的字符串:

SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options])

发送邮件。 必需的参数是RFC 822从地址字符串,RFC 822到地址字符串列表 (裸字符串将被视为具有1个地址的列表)和消息字符串。

(强调)

您应该将使用COMMASPACE加入的同一列表直接传递到SMTP.sendmail而不是传递串联的平面字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM