Python implements sending emails to QQ mailbox

Preface

First, you must understand the mailbox communication protocol SMTP protocol

SMTP (Simple Mail Transfer Protocol)
is a simple mail transfer protocol. It is a set of
rules for transmitting mail from a source address to a destination address. It controls the transfer method of letters. The SMTP protocol belongs to the TCP/IP protocol suite, which helps each computer
find the next destination when sending or relaying letters. Through the server specified by the SMTP protocol, the E-mail can be sent to the recipient's server. The whole process
only takes a few minutes. The SMTP server is an outgoing email server that follows the SMTP protocol and is used to send or relay outgoing emails. SMTP
is an application layer protocol supported by the TCP protocol that provides reliable and efficient email transmission.

Working process First, the SMTP client running on the sending mail server host initiates the establishment of a TCP connection to the SMTP server port number 25
running on the receiving mail server host .
If the receiving mail server is not currently working, the SMTP client waits for a period of time before
trying to establish the connection.

MIME email format

A simple ASCII-encoded Email format is defined in the RFC 2822 document. However, with the development of the Internet, Email only transmits simple text and cannot meet the needs of users. In order to transmit a large amount of HTML, images, sounds, and Various attachment formats, a new extended email format emerged - MIME

2. Code

import smtplib,time
from email.mime.text import MIMEText#发送文本
from email.mime.multipart import MIMEMultipart#生成多个部分的邮件体
from email.mime.application import MIMEApplication#发送图片

#定义发件人和收件人
sender='[email protected]'#发送邮箱
receivers='[email protected]'#接收邮箱
#构建邮件的主体对象
body='''
'这是一个测试文件'
<a href="www.baidu.com">点开有惊喜</a>
'''
msg=MIMEMultipart()
content=MIMEText(body,'html','utf-8')#plain以文本形式发送,html以html格式发送
msg['Subject']='test测试'#文章标题
msg['From']=sender#发送人
msg['To']=receivers#收信人
qqcode='wiluumzazwszdfafj'
msg.attach(content)#把邮件内容拼接到msg里面
#建立与邮件服务器的连接并发送邮件,qq要发多封,sleep
try:
    smtpObj=smtplib.SMTP_SSL('smtp.qq.com',465)#实例化 基于ssl,则smtplib.SMTP_SSL
    smtpObj.login(user='[email protected]',password='xxxxxxxx')
    smtpObj.sendmail(sender,receivers,msg.as_string())
    smtpObj.quit()
    print('邮件发送成功')
except:
    print('邮件发送失败')

Guess you like

Origin blog.csdn.net/qq_33655643/article/details/124485153