Send Gmail in Python

Advance preparation

You need to change the security of your Google account so that you can send emails from python.

From Google account security Login to Google-Turn on 2-step verification process, Set the app password.

セキュリティ.jpg

Connect to the SMTP server

You need to log in to Gmail's server address (smtp.gmail.com), port 587 with your Google account and password.

smtpobj = smtplib.SMTP('smtp.gmail.com', 587)
smtpobj.starttls()
smtpobj.login(sendAddress, password)

Compose an email to send

Add the content of the email to send to MIMEText. You can add the subject to ['Subject'], the sender's email address to ['From'], and the destination email address to ['To'].

msg = MIMEText(bodyText)
msg['Subject'] = subject
msg['From'] = fromAddress
msg['To'] = toAddress
msg['Date'] = formatdate()

Send email

You can send the email created by send_message.

smtpobj.send_message(msg)
smtpobj.close()

Summary

import smtplib
from email.mime.text import MIMEText
from email.utils import formatdate

sendAddress = 'My email address'
password = 'password'

subject = 'subject'
bodyText = 'Text'
fromAddress = 'Sender's email address'
toAddress = 'Destination email address'

#Connect to SMTP server
smtpobj = smtplib.SMTP('smtp.gmail.com', 587)
smtpobj.starttls()
smtpobj.login(sendAddress, password)

#Compose an email
msg = MIMEText(bodyText)
msg['Subject'] = subject
msg['From'] = fromAddress
msg['To'] = toAddress
msg['Date'] = formatdate()

#Send the created email
smtpobj.send_message(msg)
smtpobj.close()

Recommended Posts

Send Gmail in Python
Draft Gmail in Python
Send email in Python (Outlook)
Send using Python with Gmail
Create Gmail in Python without API
[Python] Create API to send Gmail
Send email via gmail with Python 3.4.3.
Quadtree in Python --2
Python in optimization
CURL in python
Geocoding in python
SendKeys in Python
Meta-analysis in Python
Unittest in python
[Python] Send email
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
[Python] Send email
Plink in Python
Constant in python
FizzBuzz in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
LiNGAM in Python
Flatten in python
flatten in python
Send email to multiple recipients in Python (Python 3)
Sorted list in Python
Daily AtCoder # 36 in Python
Clustering text in Python
Daily AtCoder # 2 in Python
Daily AtCoder # 32 in Python
Daily AtCoder # 6 in Python
Daily AtCoder # 18 in Python
Edit fonts in Python
Singleton pattern in Python
Read DXF in python
Daily AtCoder # 53 in Python
Use config.ini in Python
Daily AtCoder # 33 in Python