0

I'm trying to send mail in python using smtp and MIME. I can send one email with an attachment fine, but when I try to send many it sends the first person in the list the same email the number of people there are in the list.

# -*- coding: iso-8859-1 -*-
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from smtplib import SMTP

msg = MIMEMultipart()
msg['Subject'] = 'Email From Python with attachment'
msg['From'] = 'email1.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 with an attachment")
msg.attach(part)

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

# Create an instance in SMTP server
smtp = SMTP('localhost')

#open data file
fo = open("data.txt", "rw+")

#send email to names in file
for line in fo:
    msg['To'] = line
    # Send the email
    smtp.sendmail(msg['From'], msg['To'], msg.as_string())

From looking around it seems like the problem might lie in msg['To'] expecting a string and sendmail expecting a list. If possible I'd like to do this in a loop. If using a loop isn't the standard paradigm I'll try to use what is.

TheOneTrueSign
  • 149
  • 1
  • 2
  • 13
  • 1
    Does this help?: http://stackoverflow.com/questions/20509427/python-not-sending-email-to-multiple-addresses – Riccati Nov 25 '15 at 19:15
  • 1
    You are right, the `SendEmail` expects a list, from [Doc](https://docs.python.org/3/library/smtplib.html#smtplib.SMTP.sendmail). – user2989408 Nov 25 '15 at 19:15
  • So based off of these links it seems the best thing to do would be to iterate through the file putting all of the email addresses in the list, then changing the sendmail line to something like this :: `smtp.sendmail(msg['From'], recipientsList, msg.as_string()`. – TheOneTrueSign Nov 25 '15 at 19:31

0 Answers0