Saturday, April 7, 2018

Write Python Code to Send Email from Gmail

sendmail

In this tutorial, we will write python code to send to multiple emails. Followings are the scenario:

  • Emails will be listed in a text file
  • The Python code will read the emails and send email to each address
  • The email used is gmail

Allow Less Secure App

You must allow low secure app in your google account setting before you can run the code. In order to do that, go to https://myaccount.google.com/?pli=1, navigate to sign in and security, scroll down and enable the allow less secure apps

Write the Python Code

Now we go to the most interesting part i.e. writing the code.

Simplest Code

We will start with a very simple code to send to one account

#!/usr/bin/python

import smtplib

fromaddr = "mymail@gmail.com"
frompass = "mypass"
text = "this is the body"

email = "targetmail@gmail.com"

# login and send the email
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, frompass)
server.sendmail(fromaddr, email, text)
server.quit()

print "sent to " + email

Say you save the file to be sendmail.py. Now you can run it in terminal

$ chmod +x sendmail.py
$ ./sendmail.py
sent to targetmail@gmail.com

When you open your email, you will find a new email with (no subject) with the body as this is the body

Complete Email Content

As you notice, your program will send email without subject. To put complete email content, you should modify your program as follows

#!/usr/bin/python

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders

fromaddr = "mymail@gmail.com"
frompass = "mypass"
email = "targetmail@gmail.com"

msg = MIMEMultipart()
msg['from'] = fromaddr
msg['to'] = email
msg['Subject'] = "test mail"
body = "this is the body"
msg.attach(MIMEText(body, 'plain'))

text = msg.as_string()

# login and send the email
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, frompass)
server.sendmail(fromaddr, email, text)
server.quit()

print "sent to" + email

You can run it again

$ ./sendmail.py
sent to targetmail@gmail.com

In the target email, you will find that now you have the subject. If you want to add attachment with your email, you can add some lines as follows. But, before, create a file named emails. We will use the file as the attachment. If you use *nix, you can create the file using the following command

$ touch emails

Now add some lines in your Python code as follows

#!/usr/bin/python

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import Encoders
import os

fromaddr = "mymail@gmail.com"
frompass = "mypass"
email = "targetmail@gmail.com"

msg = MIMEMultipart()
msg['from'] = fromaddr
msg['to'] = email
msg['Subject'] = "test mail"
body = "this is the body"
msg.attach(MIMEText(body, 'plain'))

# prepare the attachment
part = MIMEBase('application', "octet-stream")
part.set_payload(open(os.getcwd() + "/emails", "rb").read())
Encoders.encode_base64(part)

part.add_header('Content-Disposition', 'attachment; filename="emails.txt"')

# attach into email
msg.attach(part)

# convert msg into string
text = msg.as_string()

# login and send the email
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, frompass)
server.sendmail(fromaddr, email, text)
server.quit()

print "sent to " + email

Now run it again

$ ./sendmail.py
sent to targetmail@gmail.com

You will find that the email now has the attachment. The name of the attachment is email.txt. As we put nothing in the emails file, the file content sent through the email will be just an empty file.

Read Target Email from File

Now we will make it more interesting by reading the target email from the text file. Create a text file using your favourite editor. In my case, I prefer to use nano. In my case, I did the followings

$ nano emails

My list of emails is something like this

firstmail@something.com
secondmail@something.com
thirdmail@something.com

Your Python code will be like this

#!/usr/bin/python

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import Encoders
import os

fromaddr = "mymail@gmail.com"
frompass = "mypass"
email = "targetmail@gmail.com"

msg = MIMEMultipart()
msg['from'] = fromaddr
msg['Subject'] = "test mail"
body = "this is the body"
msg.attach(MIMEText(body, 'plain'))


# prepare the attachment
part = MIMEBase('application', "octet-stream")
part.set_payload(open(os.getcwd() + "/emails", "rb").read())
Encoders.encode_base64(part)

part.add_header('Content-Disposition', 'attachment; filename="emails"')

# attach into email
msg.attach(part)

f = open(os.getcwd() + "/emails")

for email in f:
    msg['To'] = email

    text = msg.as_string()

    # login and send the email
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(fromaddr, frompass)
    server.sendmail(fromaddr, email, text)
    server.quit()
    print('sent to ' + email)

print "Sending email finished"

When you run the Python code, it will be

$ ./coba.py 
sent to firstmail@something.com

sent to secondmail@something.com

sent to thirdmail@something.com

Sending email finished

Thank you for reading this tutorial. Hope it is useful for you :D

No comments: