Pages

Friday, 31 January 2020

Python and Email: sending email from Gmail the simplest way


Sending email via Python's smtplib is much easier than most people think.
For setting up Gmail account and more, please refer to test-gmail-from-command-line.

$ cat gmail.py
import smtplib

smtp_server = 'smtp.gmail.com'
user = 'agent.smallstrong@gmail.com'
passwd = 'z********9'
recipient = 'smstong@126.com'
subject = 'TEST'
body = 'BODY'

# ----  mail content format ----
# From: <agent.smallstrong@gmail.com>
# To: <smstong@126.com>
# Subject: TEST
#

# BODY

msg = 'From: %s\nTo: %s\nSubject: %s\n\n%s' % (user, recipient, subject, body)

with smtplib.SMTP_SSL(smtp_server) as server:
    server.login(user, passwd)
    server.sendmail(user, recipient, msg)

No comments:

Post a Comment