Use smtp server to send mail (python)

In many scenarios, we need to send text messages or emails to specific people for notification after the code execution is completed, so the code must have the function of sending emails and text messages. Here only introduces the function part of using the smtp server to send mail. The smtp server of the 163 mailbox I used, the editing language is python3.

import smtplib
from email.mime.text import MIMEText
from email.header import Header
# from email.mime.multipart import MIMEMultipart


def mail_test():
    # 发送用户名
    sender = '[email protected]'
    # 接收方
    receiver = '[email protected]'
    # 主题
    subject = 'python email'
    # 服务器地址
    smtpserver = 'smtp.163.com'
    # 登陆名,必须与发送用户名相同,否则会报错
    username = '[email protected]'
    # 授权码
    password = '*****'
    # 发送邮件内容
    mail_body = '收到邮件请告诉我一下'
    # print('11');
    # 发送的消息 注意第二项必须为plain才能显示,如果为text,发送内容将会以二进制作为附件发送给对方。
    # 如果是想要带有格式,可以采用html格式,第二项可以配置为'html',汉字发送,第三项需要设置为'utf-8'
    msg = MIMEText(mail_body, 'plain', 'utf-8')
    # 消息的主题
    msg['Subject'] = Header(subject, 'utf-8')
    # 消息来源主要是为了让接收方知道是谁发送的邮件,如果没有这项,邮件将会被当作垃圾邮件处理,发送不成功
    msg['From'] = sender
    # 作用同'From'
    msg['To'] = receiver

    # 调用smtplib模块进行发送,这块没啥坑
    smtp = smtplib.SMTP()
    smtp.connect(smtpserver)
    smtp.login(username, password)
    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.quit()

Note that one of the authorization codes: using the program to log in is different from the webpage mailbox password. This needs to be logged in to send the mailbox to set up, here 163 mailbox as an example.

First click the menu settings, select "pop3 / smtp / imap",

In the pop-up interface, look for "Client Authorization Password" in the left column

Click "Client Authorization Password" in the navigation bar to get the following interface.

Click "Set Client Authorization Code" in the interface, select "On", and then perform "Reset Client Authorization Code" (green button) to modify the password. That password is the authorization code in the code, the one with ****** in the example.

After that, you can log in normally, and pro test is available.

Published 42 original articles · praised 4 · 10,000+ views

Guess you like

Origin blog.csdn.net/wangyhwyh753/article/details/94478715