Skip to main content

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

Comments

Popular posts from this blog

If and For in Wolfram Mathematica (with examples)

IF Condition in Wolfram Mathematica The syntax is as follows xxxxxxxxxx If [ condition , what to do if true , what to do if false ] Some examples Example 1. Simple command x x = - 3 ; If [ x < 0 , - x , x ] 3 Example 2. If condition in a function abs [ x_ ] := If [ x < 0 , - x , x ] abs /@ { - 3 , 2 , 0 , - 2 } { 3 , 2 , 0 , 2 }   For in Wolfram Mathematica The syntax is as follows For [ start , test , inc , what to do ] Some examples Example 1. Simple Loop xxxxxxxxxx For [ i = 0 , i < 4 , i ++, Print [ i ]] 0 1 2 3 Example 2. Another simple loop For [ i = 10 , i > 0 , i --, Print [ i ]] 10 9 8 7 6 5 4 3 2 1 Example 3. Print list a = { 10 , 3 , 9 , 2 } For [ i = 1 , i < 5 , i ++, Print [ a [[ i ]]]] 10 3 9 2  

Find JIRA issues mentioned in Confluence Page

I have been walking through a lot of pages in internet but have not found any answer except one. However, the answer is not complete, so I will share my experience here. This feature is very useful, especially to summarize the issues found during certain tests, where the tests are reported in a confluence page. I found that there are so many questions about this, but Atlassian seems does not want to bother with this request. I found one way to do this by the following tricks Take one JIRA issue that related to the target confluence page (in this case, say it is GET-895) Find the global ID of a JIRA issue: http://bach.dc1.scram.com:8080/rest/api/latest/issue/GET-895/remotelink It will show the JSON like this: [{"id":28293,"self":"http://bach.dc1.scram.com:8080/rest/api/latest/issue/GET-895/remotelink/28293","globalId":"appId=662e1ccf-94da-3121-96ae-053d90587b29&pageId=105485659","application":{

Mininet/Containernet Problem: Exception: Error creating interface pair (s2-eth5,s3-eth1): RTNETLINK answers: File exists

If you did not shut down the previous running mininet/containernet network (e.g. if you lose your connection to remote server), you will got the following error when you try to rerun your mininet network Traceback (most recent call last): File "./mynet.py", line 31, in <module> net.addLink(d2, s1) File "build/bdist.linux-x86_64/egg/mininet/net.py", line 403, in addLink File "build/bdist.linux-x86_64/egg/mininet/link.py", line 430, in __init__ File "build/bdist.linux-x86_64/egg/mininet/link.py", line 474, in makeIntfPair File "build/bdist.linux-x86_64/egg/mininet/util.py", line 202, in makeIntfPair Exception: Error creating interface pair (d2-eth0,s1-eth2): RTNETLINK answers: File exists In order to solve the problem, you need to clean up the previous running topology by using the following command sudo mn -c It will clean up all your cache. It will be something like this $ sudo mn -c *** Re