python发送邮件

Posted lijinglj

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python发送邮件相关的知识,希望对你有一定的参考价值。

参考:https://www.cnblogs.com/yoyoketang/p/7277259.html#4031999

一:发送测试报告给个人(不带附件)

         知识点:

         1、SMTP服务器需要身份验证(端口:465或587)

         2、POP3服务器(端口:995)

         3、先导入smtplib库用来发送邮件

         4、导入MIMEText库用来做纯文本的邮件模板

         ############163邮箱:############

         发件服务器为:smtp.163.com

如果提示163没有授权或者被拦截等信息,可以试着更改163邮箱的设置。然后使用授权码登录

 

import smtplib
from email.mime.text import MIMEText

# ----------1.跟发件相关的参数------
smtpserver = "smtp.163.com"            # 发件服务器
port = 465                                          # 端口
sender = "ljxxx@163.com"                # 账号
psw = "xxx"                         # 密码
receiver = "lixxxx@163.com"        # 接收人


# ----------2.编辑邮件的内容------
subject = "这个是主题163"
body = \'<p>这个是发送的163邮件</p>\'  # 定义邮件正文为html格式
msg = MIMEText(body, "html", "utf-8")
msg[\'from\'] = sender
msg[\'to\'] = receiver
msg[\'subject\'] = subject

# ----------3.发送邮件------
smtp = smtplib.SMTP()                                     #初始化
smtp.connect(smtpserver)                                  # 连服务器
smtp.login(sender, psw)                                     # 登录
smtp.sendmail(sender, receiver, msg.as_string())  # 发送
smtp.quit()   

############QQ邮箱:############

         发件服务器为:smtp.163.com

注意:

找到QQ邮箱授权码,打开QQ邮箱-设置-账号-POP3开启服务-开启

(如果已经开启了,不知道授权码,就点温馨提示里面的‘生成授权码’)

收到授权码后复制,保存下来,这个就可以当QQ邮箱的密码了

# coding:utf-8
import smtplib
from email.mime.text import MIMEText

# ----------1.跟发件相关的参数------
smtpserver = "smtp.qq.com"            # 发件服务器
port = 465                                          # 端口
sender = "xxxx@qq.com"                # 账号
psw = "xxxx"                         # 密码
receiver = "lixxxx@163.com"        # 接收人


# ----------2.编辑邮件的内容------
subject = "这个是主题QQ"
body = \'<p>这个是发送的QQ邮件</p>\'  # 定义邮件正文为html格式
msg = MIMEText(body, "html", "utf-8")
msg[\'from\'] = sender
msg[\'to\'] = receiver
msg[\'subject\'] = subject

# ----------3.发送邮件------
smtp = smtplib.SMTP_SSL(smtpserver, port)
smtp.login(sender, psw)                                      # 登录
smtp.sendmail(sender, receiver, msg.as_string())  # 发送
smtp.quit()                                                        # 关闭                                               # 关闭

 

二:兼容163和QQ邮箱,不带附件

需要改动的是底单部分发送邮件那块

try:
    smtp = smtplib.SMTP_SSL(smtpserver, port)   #QQ邮箱
except:
    smtp = smtplib.SMTP()                       #163邮箱
    smtp.connect(smtpserver, port)              #链接服务器
# 用户名密码
smtp.login(sender, psw)                         #登录
smtp.sendmail(sender, receiver, msg.as_string())#发送
smtp.quit()                                     #关闭

 

三:发送测试报告给单个人,兼容163和QQ邮箱,带附件

3.1上面的MIMEText只能发送正文,无法带附件,发送带附件的需要导入另外一个模块MIMEMultipart

3.2先读取要发送文件的内容,file_path是路径的参数名

3.3. file_name参数是发送的附件重新命名

# coding:utf-8
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# -----相关路径-----
#父目录:os.path.dirname(所在目录:os.path.dirname(绝对路径:os.path.realpath(__file__)))
cur_path = os.path.dirname(os.path.realpath(__file__))  #当前文件存在的路径
case_path = os.path.join(cur_path, \'test_case\')         #测试case目录
report_path = os.path.join(cur_path, \'report\')          #测试报告存放目录

# ----------1.跟发件相关的参数------

smtpserver = "smtp.qq.com"           # 发件服务器
port = 465                                           # 端口
sender = "xxx@qq.com"               # 账号
psw = "xxxx"                             # 密码
receiver = "xxxx0@163.com"        # 接收人


# ----------2.编辑邮件的内容------
# 读文件
file_path = report_path + r"\\result.html"
with open(file_path, "rb") as f:
    mail_body = f.read()

msg = MIMEMultipart()
msg["from"] = sender                             # 发件人
msg["to"] = receiver                               # 收件人
msg["subject"] = "这个我的主题"             # 主题

# 正文
body = MIMEText(mail_body, "html", "utf-8")
msg.attach(body)

# 附件
att = MIMEText(mail_body, "base64", "utf-8")
att["Content-Type"] = "application/octet-stream"
att["Content-Disposition"] = \'attachment; filename="test_report.html"\'    #附件名字filename需要和实际发送的文件名字一样哦
msg.attach(att)

# ----------3.发送邮件------
try:
    smtp = smtplib.SMTP_SSL(smtpserver, port)  # QQ邮箱
except:
    smtp = smtplib.SMTP()  # 163邮箱
    smtp.connect(smtpserver, port)  # 链接服务器
# 用户名密码
smtp.login(sender, psw)  # 登录
smtp.sendmail(sender, receiver, msg.as_string())  # 发送
smtp.quit()  # 关闭

 

四:发送测试报告给多个人,兼容163和QQ邮箱,带附件

1.上面都是发给一个收件人,那么如何一次发给多个收件人呢?只需改两个小地方

2.把receiver参数改成list对象,单个多个都是可以收到的

3.msg["to"]这个参数不能用list了,得先把receiver参数转化成字符串,如下图所示

 

# coding:utf-8
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# -----相关路径-----
#父目录:os.path.dirname(所在目录:os.path.dirname(绝对路径:os.path.realpath(__file__)))
cur_path = os.path.dirname(os.path.realpath(__file__))  #当前文件存在的路径
case_path = os.path.join(cur_path, \'test_case\')         #测试case目录
report_path = os.path.join(cur_path, \'report\')          #测试报告存放目录

# ----------1.跟发件相关的参数------

smtpserver = "smtp.qq.com"           # 发件服务器
port = 465                                           # 端口
sender = "xxxx@qq.com"               # 账号
psw = "xxxxx"                             # 密码
# receiver = "xxxxx@163.com"        # 接收人
receiver = ["xxxx@163.com", "xxxx0@126.com"]   # 多个收件人list对象

# ----------2.编辑邮件的内容------
# 读文件
file_path = report_path + r"\\result.html"
with open(file_path, "rb") as f:
    mail_body = f.read()

msg = MIMEMultipart()
msg["subject"] = "这个我的主题多人"             # 主题
msg["from"] = sender                             # 发件人
# msg["to"] = receiver                               # 收件人
msg["to"] = ";".join(receiver)             # 多个收件人list转str

# 正文
body = MIMEText(mail_body, "html", "utf-8")
msg.attach(body)

# 附件
att = MIMEText(mail_body, "base64", "utf-8")
att["Content-Type"] = "application/octet-stream"
att["Content-Disposition"] = \'attachment; filename="test_report.html"\'    #附件名字filename需要和实际发送的文件名字一样哦
msg.attach(att)

# ----------3.发送邮件------
try:
    smtp = smtplib.SMTP_SSL(smtpserver, port)  # QQ邮箱
except:
    smtp = smtplib.SMTP()  # 163邮箱
    smtp.connect(smtpserver, port)  # 链接服务器
# 用户名密码
smtp.login(sender, psw)  # 登录
smtp.sendmail(sender, receiver, msg.as_string())  # 发送
smtp.quit()  # 关闭

 

五:发送测试报告给多个人,兼容163和QQ邮箱,带附件。从配置表读取信息

         ###############lj##################

[email]
smtp_server = smtp.qq.com
port = 465
sender = xxxxx@qq.com
psw = xxxx
[receiver]
lj = xxxxx.com
lj1 = xxxxx.com

#############read.py############# 

import os
import configparser

cur_path = os.path.dirname(os.path.realpath(__file__))   #获取当前文件所在路径
configPath = os.path.join(cur_path, "lj")  #拼接出文件路径
conf = configparser.ConfigParser()
conf.read(configPath)  #读取配置文件lj.ini

# 获取指定的section, 指定的option的值
smtp_server = conf.get("email", "smtp_server")
sender = conf.get("email", "sender")
psw = conf.get("email", "psw")
port = conf.get("email", "port")

receiver1 = conf.items(\'receiver\')
receiver = list()
for i in range(len(receiver1)):
    y = receiver1[i][-1]
    receiver.append(y)

#############run3.py############# 

import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# 父目录:os.path.dirname(所在目录:os.path.dirname(绝对路径:os.path.realpath(__file__)))
cur_path = os.path.dirname(os.path.realpath(__file__))  #当前文件存在的路径
case_path = os.path.join(cur_path, \'test_case\')         #测试case目录
report_path = os.path.join(cur_path, \'report\')          #测试报告存放目录


def send_mail(sender, psw, receiver, smtpserver, port):
    \'\'\'第三步:发送最新的测试报告内容\'\'\'
    #读文件
    file_path = report_path + r"\\result.html"
    with open(file_path, "rb") as f:
        mail_body = f.read()

    # 定义邮件内容
    msg = MIMEMultipart()
    msg[\'Subject\'] = u"duoren"  #主题
    msg["from"] = sender     #发件人
    # msg["to"] = receiver      #收件人
    msg[\'to\'] = ",".join(receiver)

    #正文
    body = MIMEText(mail_body, _subtype=\'html\', _charset=\'utf-8\')
    msg.attach(body)

    # 添加附件
    att = MIMEText(mail_body, "base64", "utf-8")
    att["Content-Type"] = "application/octet-stream"
    att["Content-Disposition"] = \'attachment; filename= "report.html"\'
    msg.attach(att)

    try:
        smtp = smtplib.SMTP_SSL(smtpserver, port)   #QQ邮箱
    except:
        smtp = smtplib.SMTP()                       #163邮箱
        smtp.connect(smtpserver, port)              #链接服务器
    # 用户名密码
    smtp.login(sender, psw)                         #登录
    smtp.sendmail(sender, receiver, msg.as_string())#发送
    smtp.quit()                                     #关闭
    print(\'test report email has send out !\')

if __name__ == "__main__":
    # 邮箱配置
    from config import read
    sender = read.sender
    psw = read.psw
    smtp_server = read.smtp_server
    port = read.port
    receiver = read.receiver
    # print(sender, psw, smtp_server, port, receiver1)
    send_mail(sender, psw, receiver, smtp_server, port)  # 发送报告

 

欢迎指正

 

以上是关于python发送邮件的主要内容,如果未能解决你的问题,请参考以下文章

超实用的php代码片段

Javascript - 使用 HTML 片段通过电子邮件发送 JSON 输出

Github 大牛封装 Python 代码,实现自动发送邮件只需三行代码

C#和ASP.NET通过Gmail账户发送邮件的代码

python笔记- 发送邮件

实现Python代码发送邮件