Python教程

python发送邮件的简单使用

本文主要是介绍python发送邮件的简单使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

主代码如下:

点击查看代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/12/26 9:46 上午
# @Author  : Ayden
# @Site    : 
# @File    : send_email.py
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
import smtplib
import pathlib
from conf.setting import *
from common.log import Log

log = Log().log()

def send_mail(host="xxxxxx", port=None, title=None, send_files=None, content=None):
    if not content:
        title = "车联网接口自动化测试报告"
    if not content:
        content = "     \n\n附件为车联网云平台接口自动化测试报告,请使用浏览器进行查看,访问地址为:\n" \
                  "     http://{}:{}\n" \
                  "\n\n本邮件为自动发出,请勿回复".format(host, port)
    mail_host = send_email["mail_host"]
    mail_port = send_email["mail_port"]
    mail_user = send_email["mail_user"]
    mail_password = send_email["mail_pass"]
    # log.debug("发件信息为:{}".format(send_email))
    try:
        msg = MIMEMultipart()
        msg['Subject'] = title
        msg['To'] = ",".join(receive_email)
        print(msg['To'])
        msg['From'] = mail_user
        body = MIMEText(content, 'plain', 'utf-8')
        if send_files:
            #for send_file in send_files:
            part_attach = MIMEApplication(open(send_files, 'rb').read())  # 打开附件
            # 为附件命名
            part_attach.add_header('Content-Disposition', 'attachment', filename=pathlib.Path(send_files).name)
            # 添加附件
            msg.attach(part_attach)
        msg.attach(body)
        smtp = smtplib.SMTP(mail_host, mail_port)
        smtp.starttls()
        smtp.login(mail_user, mail_password)
        smtp.sendmail(mail_user, receive_email, msg.as_string())
        # log.debug("邮件发送成功")
        smtp.quit()
    except Exception as e:
        log.debug("邮件发送失败,原因是{}".format(e))

其中setting配置如下:

点击查看代码
# 发件人电子邮箱
send_email = {"mail_host": "smtp.163.com", "mail_port": 25, "mail_user": "api_auto_test@163.com",
             "mail_pass": "XSJLZTQHSMAKPCMX"}
# 收件人电子邮箱
receive_email = ['api_auto_test@163.com', 'lizhaoyong94@163.com']

备注:以上日志模块请自行去除

这篇关于python发送邮件的简单使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!