2

I am new to python and am trying to read values send email using smtplib. Here is the format of my csv file -

Name,Email,Message  
A,[email protected],Message1  
B,[email protected],Message2  
C,[email protected],Message3  

I need to come up with a Python Script that reads the csv columns and sends out emails to each member from the email column with corresponding Message text in the email body

3 Answers 3

4

Assume you're using Python-2.x.

You can use the smtplib module to send the email and the csv module to read the csv file.

Besides, to use smtplib, you must have a email address used to send the emails, no matter the email is Yahoo mail or Gmail or whatever else.

Some sample codes read as follows:

#!/usr/bin/python

import csv
import smtplib
from email.mime.text import MIMEText
from email.Header import Header

def sendmail(info_list):
    msg = MIMEText(info_list[2], "html", "utf-8")
    msg['Subject'] = Header("YOUR SUBJECT", "utf-8")
    msg['From'] = "[email protected]"
    msg['To'] = info_list[1]
    s = smtplib.SMTP("smtp.XXX.com")
    s.ehlo()
    s.starttls()
    s.login("YOUR EMAIL USERNAME", "YOUR EMAIL PASSWORD")
    s.sendmail("FROM_WHOM", info_list[1], msg.as_string())

def main():
    with open("msg.csv", "rb") as csvfile:
        msg_reader = csv.reader(csvfile)
        msg_reader.next()
        map(lambda x: sendmail(x), msg_reader)

if __name__ == "__main__":
    main()
Sign up to request clarification or add additional context in comments.

1 Comment

I Using above code only one Problem I have face mail not sent until I converted in list map(lambda x: sendmail(x), msg_reader)
2

Python comes with a great module called smtplib. It is used for Simple Mail Transfer Protocols.

import smtplib
sender = '[email protected]'
receivers = ['[email protected]']

message = """From: From Person <[email protected]>
To: To Person <[email protected]>
Subject: SMTP e-mail test

This is a test e-mail message.
"""

try:
   smtpObj = smtplib.SMTP('localhost')
   smtpObj.sendmail(sender, receivers, message)         
   print("Successfully sent email")
except SMTPException:
   print("Error: unable to send email")

Code credit http://www.tutorialspoint.com/python/python_sending_email.htm

Comments

2

SMTP is a great module, but not so user friendly.

yagmail tries to make it all a little easier.

In your case I would use:

import yagmail

yag = yagmail.Connect('username', 'password')

with open("msg.csv", "rb") as csvfile:
    csv_reader = csv.reader(csvfile)
    csv_reader.next()

    for line in csv_reader:
        for name, email, message in line.strip().split(','):
            yag.send(email, subject = name, contents = message) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.