以下文章会介绍用 Python 使用 smtplib 连接到 Gmail 的 SMTP 服务器, 并发出电子邮件的方法。
但在开始前, Google 帐号是使用双重认证密码, 如果直接在 Python code 内输入 Google 密码, 会回传以下报错:
smtplib.SMTPAuthenticationError: (534, b’5.7.9 Application-specific password required. Learn more at\n5.7.9 https://support.google.com/mail/?p=InvalidSecondFactor q29-20020aa7983d000000b0056c47a5c34dsm3753436pfl.122 – gsmtp’)
所以要先到 Google 帐户, 选取左边的 “安全性” 。
按下在“登入 Google”底下的 [应用程式密码], 然后需要 Google 帐号密码。
在 “选取应用程式” 选择 “邮件”
“选取装置” 选择 “其他 (自订名称”, 输入自已析别的名称, 例如 “Python”.
按 “产生”
这时便会弹出一个应用程式的专属密码, 把这个密码复制下来, 稍后在 Python 的程式码需要用上。
现在可以写 Python 的程式, 以下程式码会使用 smtplib 模组, 具体写法如下:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
#!/usr/bin/python3.6 import smtplib # Google login gmail_id = 'Your Gmail Account' gmail_passwd = 'Google App Password' to_address = 'To Email Address' # email content subject = "email subject" text = "email message" # creates SMTP session s = smtplib.SMTP('smtp.gmail.com', 587) # start TLS for security s.starttls() # gmail username and password s.login(gmail_id, gmail_passwd) message = 'Subject: {}\n\n{}'.format(subject, text) # sending the mail s.sendmail(gmail_id, to_address, message) # terminating the session s.quit() |
在上面的程式码, 需要修改 gmail_id, gmail_passwd, to_address, subject 及 text 变量:
gmail_id: Gmail 登入名称.
gmail_passwd: 在 Google Account 建立的应用程式密码.
to_address: 收件人的电邮地址.
subject: 电子邮件标题.
text: 电子邮件内容.
以上程式会连接到 Gmail 的 smtp 服务器发出电子邮件, 而寄出的内容会存放在 Gmail 的寄件备份。