Python uses SMTP to send emails

In the days when you were full of ambition, you jumped on the shoulders of giants and found that when doing automated testing, people hope that after a round of testing, there will be a reminder to inform people of the test results, so emails are used in the testing framework Send this function
To realize this function, two steps are required, one is the SMTP service configuration, and the other is the implementation of the code block
1. SMTP service configuration
Email sending needs to use the SMTP server, the official explanation is: SMTP (Simple Mail Transfer Protocol ) is the Simple Mail Transfer Protocol, which is a set of rules used to transmit mail from the source address to the destination address, and it controls the transfer mode of the letter. There are 163, qq, etc. available free mailbox configurations.

Choose one to set (I chose 163 NetEase mailbox)
and open the registered 163 mailbox

Find the setting-POP3/SMTP/IMAP
insert image description here
to open any one, as long as it includes SMTP, you can
insert image description here
continue to open it
insert image description here
. Scan the QR code with 163 mailbox, and you will jump to the page for sending SMS. After sending, click I have sent, and the authorization code will be generated and return to the
insert image description here
beginning . page, see the following part, then the SMTP service configuration is complete, Wuhu ~
insert image description here
next start code implementation

2. Implementation of the code block
Refer to the code block of the giant , #—is what you need to fill in according to the situation

class SendEmail(object):
    def __init__(self, username, passwd, recv, title, content,
                 file=None, ssl=False,
                 email_host='smtp.163.com', port=25, ssl_port=465):
        self.username = username  # 用户名
        self.passwd = passwd  # 授权码
        self.recv = recv  # 收件人,多个要传list ['[email protected]','[email protected]]
        self.title = title  # 邮件标题
        self.content = content  # 邮件正文
        self.file = file  # 附件路径,如果不在当前目录下,要写绝对路径
        self.email_host = email_host  # smtp服务器地址
        self.port = port  # 普通端口
        self.ssl = ssl  # 是否安全链接
        self.ssl_port = ssl_port  # 安全链接端口

    def send_email(self):
        msg = MIMEMultipart()
        # 发送内容的对象
        if self.file:  # 处理附件的
            file_name = os.path.split(self.file)[-1]  # 只取文件名,不取路径
            try:
                f = open(self.file, 'rb').read()
            except Exception as e:
                raise Exception('附件打不开!!!!')
            else:
                att = MIMEText(f, "base64", "utf-8")
                att["Content-Type"] = 'application/octet-stream'
                # base64.b64encode(file_name.encode()).decode()
                new_file_name = '=?utf-8?b?' + base64.b64encode(file_name.encode()).decode() + '?='
                # 这里是处理文件名为中文名的,必须这么写
                att["Content-Disposition"] = 'attachment; filename="%s"' % (new_file_name)
                msg.attach(att)
        msg.attach(MIMEText(self.content))  # 邮件正文的内容
        msg['Subject'] = self.title  # 邮件主题
        msg['From'] = self.username  # 发送者账号
        msg['To'] = ','.join(self.recv)  # 接收者账号列表
        if self.ssl:
            self.smtp = smtplib.SMTP_SSL(self.email_host, port=self.ssl_port)
        else:
            self.smtp = smtplib.SMTP(self.email_host, port=self.port)
        # 发送邮件服务器的对象
        self.smtp.login(self.username, self.passwd)
        try:
            self.smtp.sendmail(self.username, self.recv, msg.as_string())
            pass
        except Exception as e:
            print('出错了。。', e)
        else:
            print('发送成功!')
        self.smtp.quit()


if __name__ == '__main__':
    m = SendEmail(
        username='',#---这里填发送者邮箱,我的是163邮箱
        passwd='',#---这里填发送者的授权码,我配置的也是163的授权码
        recv=[''],#---接收者邮箱
        title='hhhhh',#---根据所需填
        content='测试发送邮件',#---根据所需填
        file=r'/Users/user/Desktop/test/v2-5ec81fb70b0df9bc9fbde20374bd0bd3_r.jpg',#---这个是自己文件的路径
        ssl=True,**加粗样式**
    )
    m.send_email()

After running,
insert image description here
you should immediately check to see if the sender has sent it truthfully.
insert image description here
Milk thinking! Then I ran to the receiving party to see if they received it truthfully. It’s
insert image description here
amazing (cross the waist)
3. Children❓At
first, I had a doubt whether this SMTP service needs to be set up in both the sender’s and receiver’s mailboxes or just select One party’s mailbox is set, for example, my sender uses 163, and the receiver uses gmail, so should I set both or only one party?

Harmful! Facts have proved that I was thinking too much.
When I ignored my doubts, I bit the bullet and set the 163 first, and then uploaded the code, and found that it can be realized, so the answer is that I only need to set one, um!

Guess you like

Origin blog.csdn.net/z12347891/article/details/118339545