Skip to content

[Python] Use SMTP to send an email via Gmail

Last Updated on 2021-04-11 by Clay

The modern life has disappeared from Gmail, sending mails to the professors has become the most important means of communication for graduate students.

In my graduate life, I have to switch between Linux and Windows, so I have been worried about the backup of my files. I have an FTP server, but I still need more way to backup.

Once in a typhoon day, I finally angry when I used Teamviewer remote connection.

Why! Why the delay of Teamviewer is too slowly! Our professor's mail is very picky and can't be wrong!

And use terminal ssh to enter the server can't send any mail. In fact I know it can but I always blocked by the firewall.

Finally, I understood, I want to write a program to send mail from Gmail!

So I generated this note. In order to be afraid of forgetting in future, I have to record it here.

And then we start!


SMTP

First, if you search for "Python" and "Gmail", the first thing you see is "SMTP".

What is "SMTP"?

SMTP (Simple Mail Transfer Protocol), as its name suggests, is actually a "simple mail transfer protocal".

To call this protocol in Python and use it to send mail, you can use this module: smtplib.

There is no need to download by pip.

We get a look for sending mail from Gmail:

# -*- coding: utf-8 -*-
import json
from email.mime.text import MIMEText
import smtplib


# Account infomation load
account = json.load(open('Account.json', 'r', encoding='utf-8'))
gmailUser = account['Account']
gmailPasswd = account['password']
to = [account['Account'], '[email protected]', '[email protected]']

# Create message
emails = [t.split(',') for t in to]
message = MIMEText('Give me a Test!', 'plain', 'utf-8')
message['Subject'] = 'Single Test'
message['From'] = gmailUser
message['To'] = ','.join(to)

# Set smtp
smtp = smtplib.SMTP("smtp.gmail.com:587")
smtp.ehlo()
smtp.starttls()
smtp.login(gmailUser, gmailPasswd)

# Send msil
smtp.sendmail(message['From'], message['To'], message.as_string())
print('Send mails OK!')


For not to reveal my Gmail address, I used the account.json file created under the current folder, which has my account password Hahahaha.

# Account infomation load
account = json.load(open('Account.json', 'r', encoding='utf-8'))
gmailUser = account['Account']
gmailPasswd = account['password']
to = [account['Account'], '[email protected]', '[email protected]']


So you can imagine that account['Account'] is my Gmail address, and account['password'] is the password for my account. "To" is all the objects I want to sent, the format is data type "List".

# Create message
emails = [t.split(',') for t in to]
message = MIMEText('Give me a Test!', 'plain', 'utf-8')
message['Subject'] = 'Single Test'
message['From'] = gmailUser
message['To'] = ','.join(to)


In here, we use MIMEText() just imported to enter the content we want to send.

message['Subject']: Mail title
message['From']: Sender
message['To']: addressee

# Set smtp
smtp = smtplib.SMTP("smtp.gmail.com:587")
smtp.ehlo()
smtp.starttls()
smtp.login(gmailUser, gmailPasswd)


SMTP, as mentioned above, is a simple mail transfer protocol, where we use the host of Gmail ("smtp.gmail.com:587")

Port 587 is decided by Google.

smtp.ehlo(): Respond to the transfer server.
smtp. starttls(): Requires encryption.
smtp.login(): Login our Gmail account.

# Send msil
smtp.sendmail(message['From'], message['To'], message.as_string())
print('Send mails OK!')


The last is sendmail(). There are only need two things: Sender and addressee.

So we can receive our own mail! (because my addressee is also myself)

Send mails OK!

See "Send mails OK!" You know that the mail has been sent.

Result.

Mail with attached file

# -*- coding: utf-8 -*-
import json
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib


# Account infomation load
account = json.load(open('Account.json', 'r', encoding='utf-8'))
gmailUser = account['Account']
gmailPasswd = account['password']
to = [account['Account']]

emails = [t.split(',') for t in to]

# Create message
message = MIMEMultipart()
message['Subject'] = 'Single Test'
message['From'] = gmailUser
message['To'] = ','.join(to)

# Mail content
message.attach(MIMEText('Give me a Test!', 'plain', 'utf-8'))

# File
file = MIMEText(open('a.txt', 'r', encoding='utf-8').read(), 'base64', 'utf-8')
file['Content-Type'] = 'application/octet-stream'
file['Content-Disposition'] = 'attachment; filename=test.txt'
message.attach(file)

# Set smtp
smtp = smtplib.SMTP("smtp.gmail.com:587")
smtp.ehlo()
smtp.starttls()
smtp.login(gmailUser, gmailPasswd)

# Send mail
smtp.sendmail(message['From'], message['To'], message.as_string())
print('Send mails OK!')


The biggest difference:

# Create message
message = MIMEMultipart()
message['Subject'] = 'Single Test'
message['From'] = gmailUser
message['To'] = ','.join(to)


We want to carry the file in our mail, we are going to initialize MIMEMultipart().

Then we add a new file under the current folder: a.txt. And write the following paragraph in it:

Today is a nice day!
# File
file = MIMEText(open('a.txt', 'r', encoding='utf-8').read(), 'base64', 'utf-8')
file['Content-Type'] = 'application/octet-stream'
file['Content-Disposition'] = 'attachment; filename=test.txt'
message.attach(file)

# Set smtp
smtp = smtplib.SMTP("smtp.gmail.com:587")
smtp.ehlo()
smtp.starttls()
smtp.login(gmailUser, gmailPasswd)

# Send mail
smtp.sendmail(message['From'], message['To'], message.as_string())
print('Send mails OK!')


The process of setting up smtp and send mail has not changed, but this time we have to bring the file.

MIMEText(open('a.txt', 'r', encoding='utf-8').read(), 'base64', 'utf-8')

Put a.txt.

filename=test.txt

This part of the file name can be taken by yourself, of course, you can also take a.txt as usual. This affects the name of the file you received in Gmail.

Then we execute the program and should see the message sent!

Tags:

Leave a Reply