Python send mail via SMTP

Python version: Python3.5.2

Introduction

SMTP is a protocol for sending emails. Python has built-in support for SMTP, which can send plain text emails, HTML emails, and emails with attachments.

Python supports SMTP with two modules: smtplib and email. Email is responsible for constructing emails, and smtplib is responsible for sending emails.

I use the QQ mailbox to complete this experiment. First, I should configure my own mailbox to enable the SMTP function. The specific steps are as follows:

Log in to the home page of QQ mailbox, find the setting function:
enter the setting, switch to the account tab:
pull down to find the following options, and enable the SMTP function:

After successful activation, an authorization code will be generated to log in to the SMTP server. This authorization code is not unique, if you forget it, you can click to generate it again.

The experimental source code is as follows

__Author__ = "Lance#"

# -*- coding = utf-8 -*-

from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr

import smtplib

def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))

from_addr = '[email protected]'
password = '你的授权码'
to_addr = '[email protected]'
smtp_server = 'smtp.qq.com'

#要发送的消息
SendMsg = 'This is SMTP test.'

#构造一个 MIMEText 对象
msg = MIMEText(SendMsg, 'plain', 'utf-8')

#依次填充对象的各个选项
msg['From'] = _format_addr('Python <%s>' % from_addr)
msg['To'] = _format_addr('User <%s>' % to_addr)
msg['Subject'] = Header('This is SMTP test.', 'utf-8').encode()

#构造 SMTP 服务器,QQ 邮箱的 SMTP 端口为 465 且为 SSL 加密协议
server = smtplib.SMTP_SSL(smtp_server, 465)

#启用该选项,可以打印出和SMTP服务器交互的所有信息
server.set_debuglevel(1)
server.login(from_addr, password)

#发送邮件, 此处的 to_addr 可以是一个 list,可以给多人发送
server.sendmail(from_addr, [to_addr], msg.as_string())

#退出 SMTP 服务器
server.quit()

The mailbox for receiving mail can be set to be the same as the sender's address, so that after the normal operation of the program ends, your mailbox can receive the mail just sent.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325063541&siteId=291194637