-1

I read a list of emails in a txt file and sent it from my smtp server.

I am using the same email address for From: and To: which is example@email.com

So, all emails in txt file are: example@email.com

I can receive all the emails from my txt file. My problem is the following:

The subject field is blank and the field To: looks like e,x,a,m,p,l,e@,e,m,a,i,l,.,c,o,m instead of example@email.com

What I am doing wrong?

This is my python code.

import smtplib

def send_email(TOADDRS):

FROMADDR = "example@email.com"
LOGIN    = FROMADDR
PASSWORD = "password"
SUBJECT  = "Welcome to Stack Overflow"

server = smtplib.SMTP('smtp.example.com',587)
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.login(LOGIN, PASSWORD)

msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n"
   % (FROMADDR, ", ".join(TOADDRS), SUBJECT) )
msg += """ This a test \r\n"""

server.sendmail(FROMADDR, TOADDRS, msg)
server.quit()

if name == "main":

f= open("email.txt","r")
linea=f.readline()
while linea !="":
 send_email(linea)
 linea = f.readline()
f.close()
  • You're passing one email id at a time to `send_mail`, so there's no need to call `','.join` there. And don't forget to strip `'\n'` from `linea`. – Ashwini Chaudhary Jan 08 '15 at 18:54

1 Answers1

0

I think you're going about this a bit of the wrong way. An easier way would be to:

import smtplib
from email.mime.text import MIMEText

with open ("email.txt", "r") as myfile:
    while linea !="":
        data=myfile.readline().replace('\n', '')
        send_email(data)

def send_email(TOADDRS):    
    FROMADDR = "example@email.com"
    LOGIN    = FROMADDR
    PASSWORD = "password"
    SUBJECT  = "Welcome to Stack Overflow"
    BODY = "Test body"


    msg = MIMEText(BODY)
    msg['Subject'] = SUBJECT
    msg['From'] = 'example@email.com'
    msg['To'] = TOADDRS
    send = smtplib.SMTP('smtp.example.com',587)
    send.set_debuglevel(1)
    send.ehlo()
    send.starttls() 
    send.login(LOGIN, PASSWORD)
    send.sendmail(msg['From'], msg['To'], msg.as_string())
    send.quit()

That's off the top of my head and it should work for you. You may want to read the data from the file all at once into a list and then iterate through the list. It would be much more efficient. I'm just trying to give you a look at how this should be working.