Send a mail with Python Script!
--
Intro:
Sending a mail with python is an interesting thing to do because it saves you the stress of opening your browser especially if the mail is brief ( that’s not a limitation in our code though). This tutorial explains:
- How to send a simple email
- Sending mail to more than one recipient
- Attaching files of any type
Let’s get started
Gmail made some security changesrecently. You now have to allow “less secure apps” on your account. Otherwise, you won’t be able to connect to it with your python script. ] We’ll be using a built-in library called smtplib. You don’t need to install it. Let’s import it
import smtplib
Next we need to setup our server, login, sendmail and quit from server:
server = smtplib.SMTP_SSL(“smtp.gmail.com”, 465)
server.starttls()
server.login("YOUR EMAIL ADDRESS", "YOUR PASSWORD")
msg = "YOUR MESSAGE!"
server.sendmail("YOUR EMAIL ADDRESS", "THE EMAIL ADDRESS TO SEND TO", msg)
server.quit()
On line 1 in the code above, it’s the parameters for the Gmail server. First, the server location (or its ip address), then the port to use (you could either use 465 or 587. Also note that `server= smtplib.SMTP_SSL()
can also be `server = smtplib.SMTP()
if you have an email address from another service, like Yahoo for example, you have to find the corresponding parameters. On line 2, there’s a security function, needed to connect to the Gmail server. It will protect your password. Fill up all the necessary info and run the code. Kaboom! Your email is sent.
More Elaborate
For a more elaborate mail, with subject and body part we’ll be using two more modules. With the code below, you will send a clean email, with a sender, a receiver and a subject line. To do this, weneed two more modules: email.MIMEMultipart and email.MIMEText. They are part of the basic Python libraries. No need to install them.
import smtplibfrom email.MIMEMultipart import MIMEMultipartfrom email.MIMEText import MIMETextfromaddr = "YOUR ADDRESS"toaddr = "ADDRESS YOU WANT TO SEND TO"msg = MIMEMultipart()msg['From'] = fromaddrmsg['To'] = toaddrmsg['Subject'] = "SUBJECT OF THE MAIL"body = "YOUR MESSAGE HERE"msg.attach(MIMEText(body, 'plain'))server = smtplib.SMTP('smtp.gmail.com', 587)server.starttls()server.login(fromaddr, "YOUR PASSWORD")text = msg.as_string()server.sendmail(fromaddr, toaddr, text)server.quit()
Fill in the necessary parameters and run the code. Boom! You just sent a mail with a subject and body part.
For Multiple recipients
Let toAddr be a list and input all your receipients.
toAddr = ['eamail1', 'email2', 'email3']
Attaching a File
We are moving on to the next cool stuff. Attaching a file we need some extra modules to be able to send any kind of file it may be in our computer. Dont forget to allow “less secure apps” on your Gmail account before running your script. The essential step is to convert the file into a Base64 before sending it. This code works for text files, pdf files, images, audio files and video files!
import smtplibfrom email.MIMEMultipart import MIMEMultipartfrom email.MIMEText import MIMETextfrom email.MIMEBase import MIMEBasefrom email import encodersfromaddr = "YOUR EMAIL"toaddr = "EMAIL ADDRESS YOU SEND TO"msg = MIMEMultipart()msg['From'] = fromaddrmsg['To'] = toaddrmsg['Subject'] = "SUBJECT OF THE EMAIL"body = "TEXT YOU WANT TO SEND"msg.attach(MIMEText(body, 'plain'))filename = "NAME OF THE FILE WITH ITS EXTENSION"attachment = open("PATH OF THE FILE", "rb")part = MIMEBase('application', 'octet-stream')part.set_payload((attachment).read())encoders.encode_base64(part)part.add_header('Content-Disposition', "attachment; filename= %s" % filename)msg.attach(part)server = smtplib.SMTP('smtp.gmail.com', 587)server.starttls()server.login(fromaddr, "YOUR PASSWORD")text = msg.as_string()server.sendmail(fromaddr, toaddr, text)server.quit()
This code above sends an attached file when run. But note the following things:
- Use ‘r’ to normalize your file path not to cause errors e.g
`(r'C:\User\users\Desktop\titanicpic.jpg')
- Don’t forget the gmail permit
- Checkout Mime package documentation https://docs.python.org/2/library/email.mime.html
- To send attached file to multiple recipient we’ll employ a forloop
for addr in toAddr:
filename = "NAME OF THE FILE WITH ITS EXTENSION" attachment = open("PATH OF THE FILE", "rb") part = MIMEBase('application', 'octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % filename) msg.attach(part)
server.sendmail()
server.quit()
Below is a more integrated code that allows you to perform this operations combined together in one script. For any question you can reachout to me on twitter @elseagle Don’t forget to clap also. Thank you for reading.