简体   繁体   中英

Send an email having an attachment for multiple addresses in python

I wrote the below code for sending an email to multiple addresses.... But i am able to send the mail for only first address in the list...could give me exact reason and solution for it. Thanks in advance!!

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 expects a list of recipients , but you're passing a string with concatenated email addresses:

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

Send mail. The required arguments are an RFC 822 from-address string, a list of RFC 822 to-address strings (a bare string will be treated as a list with 1 address), and a message string.

(emphasis added)

You should pass the same list you join with COMMASPACE directly to SMTP.sendmail instead of passing the concatenated flat string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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