使用python发送邮件

在发送邮箱前 要开启自己的SMTP服务 QQ 邮箱一般默认关闭SMTP服务,得先去开启它。打开https://mail.qq.com/,登录你的邮箱。然后点击位于顶部的【设置】按钮,选择【账户设置】,然后下拉到这个位置。开启POP3/SMTP服务,验证后会给到一个授权码,后续服务端用该授权码登录邮箱。

之后就可以发邮箱啦:

文本邮件

import smtplib
# email 用于构建邮件内容
from email.mime.text import MIMEText
# 构建邮件头
from email.header import Header

# 发信方的信息:发信邮箱,QQ 邮箱授权码
from_addr = '*******@qq.com'  # 发生者的邮箱  您的qq邮箱
password = '*******'    # 刚才短信获取到的授权码
# 收信方邮箱
to_addr = '********@163.com'
# 发信服务器
smtp_server = 'smtp.qq.com'

# 邮箱正文内容,第一个参数为内容,第二个参数为格式(plain 为纯文本),第三个参数为编码
msg = MIMEText('使用python发送邮件测试', 'plain', 'utf-8')
# 邮件头信息
msg['From'] = Header('周**')  # 发送者
msg['To'] = Header('马大哈')  # 接收者
subject = 'Python SMTP 邮件测试' # 主题
msg['Subject'] = Header(subject, 'utf-8')  # 邮件主题
smtpobj = smtplib.SMTP_SSL(smtp_server)  # 创建对象
try:
# 建立连接--qq邮箱服务和端口号(可百度查询)
    smtpobj.connect(smtp_server, 465)
# 登录--发送者账号和口令
    smtpobj.login(from_addr, password)
# 发送邮件
    smtpobj.sendmail(from_addr, to_addr, msg.as_string())
print("邮件发送成功")
except smtplib.SMTPException:
    print("无法发送邮件")
finally:
# 关闭服务器
    smtpobj.quit()

如图:

附件邮件

import smtplib
# email 用于构建邮件内容
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# 构建邮件头
from email.header import Header

fromaddr = '*****@qq.com'   # 发送者
password = '*****corbafe'   # 授权码
toaddrs = ['*****16@163.com', '*****71@qq.com'] # 收件人

content = '在干嘛呢. 亲'
textApart = MIMEText(content)

imageFile = 'img.png'  # 图片文件
imageApart = MIMEImage(open(imageFile, 'rb').read(), imageFile.split('.')[-1])
imageApart.add_header('Content-Disposition', 'attachment', filename=imageFile)

# pdfFile = '算法设计与分析基础第3版PDF.pdf'
# pdfApart = MIMEApplication(open(pdfFile, 'rb').read())
# pdfApart.add_header('Content-Disposition', 'attachment', filename=pdfFile)

# zipFile = '算法设计与分析基础第3版PDF.zip'
# zipApart = MIMEApplication(open(zipFile, 'rb').read())
# zipApart.add_header('Content-Disposition', 'attachment', filename=zipFile)

m = MIMEMultipart()
m.attach(textApart)
m.attach(imageApart)
# m.attach(pdfApart)
# m.attach(zipApart)
m['Subject'] = 'title'

try:
    server = smtplib.SMTP('smtp.qq.com')
    server.login(fromaddr, password)
    server.sendmail(fromaddr, toaddrs, m.as_string())
    print('success')
    server.quit()
except smtplib.SMTPException as e:
    print('error:', e)  # 打印错误

如图:

html邮件 表格

 import smtplib
# email 用于构建邮件内容
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import datetime
import pandas as pd

yesterday = '2023'  # 参数
teacher_name = 'zhouxinxin'  # 参数
dept_name = '邮箱部'  # 参数
new_time = str(datetime.datetime.now().year) + '年' + str(datetime.datetime.now().month) + '月' + str(
datetime.datetime.now().day) + '日'
# pd.set_option('display.max_colwidth', -1)
columns = ['一级分类', '二级分类', '三级分类', '科目分类', '科目名称', '预算金额(万元)', '备注', '课题编号']
list = [[1,2,3,4,5,6,7,8],[9,10,11,12,13,14,15,16]]
filter_merge_data = pd.DataFrame(list, columns=columns)
df_html = filter_merge_data.to_html(escape=False)  # DataFrame数据转化为HTML表格形式
head = \
"""
        <head>
            <meta charset="utf-8">
            <STYLE TYPE="text/css" MEDIA=screen>
                table.dataframe {
                    border-collapse: collapse;
                    border: 2px solid #a19da2;
                    /*居中显示整个表格*/
                    margin: auto;
                }
                table.dataframe thead {
                    border: 2px solid #91c6e1;
                    background: #f1f1f1;
                    padding: 10px 10px 10px 10px;
                    color: #333333;
                }
                table.dataframe tbody {
                    border: 2px solid #91c6e1;
                    padding: 10px 10px 10px 10px;
                }
                table.dataframe tr {
                }
                table.dataframe th {
                    vertical-align: top;
                    font-size: 14px;
                    padding: 10px 10px 10px 10px;
                    color: #105de3;
                    font-family: arial;
                    text-align: center;
                }
                table.dataframe td {
                    text-align: center;
                    padding: 10px 10px 10px 10px;
                }
                body {
                    font-family: 宋体;
                }
                h1 {
                    color: #5db446
                }
                div.header h2 {
                    color: #0002e3;
                    font-family: 黑体;
                }
                div.content h2 {
                    text-align: center;
                    font-size: 28px;
                    text-shadow: 2px 2px 1px #de4040;
                    color: #fff;
                    font-weight: bold;
                    background-color: #008eb7;
                    line-height: 1.5;
                    margin: 20px 0;
                    box-shadow: 10px 10px 5px #888888;
                    border-radius: 5px;
                }
                h3 {
                    font-size: 22px;
                    background-color: rgba(0, 2, 227, 0.71);
                    text-shadow: 2px 2px 1px #de4040;
                    color: rgba(239, 241, 234, 0.99);
                    line-height: 1.5;
                }
                h4 {
                    color: #e10092;
                    font-family: 楷体;
                    font-size: 20px;
                    text-align: center;
                }
                td img {
                    /*width: 60px;*/
                    max-width: 300px;
                    max-height: 300px;
                }
            </STYLE>
        </head>
        """
body = \
"""
        <body>
        <div align="center" class="header">
            <!--标题部分的信息-->
            <h1 align="center">关于下达{yesterday}年各部门/专项经费预算指标的通知</h1>
        </div>
        <hr>
        <div class="content">
            <!--正文内容-->
            <h2> </h2>
            <div>
                <h4>{teacher_name}老师  您好:</h4>
                <h4>学校党委会已批准{yesterday}年各部门/专项预算方案,财务计划处已将预算指标导入ARP系统,请各位负责人及时查看,明细如下:    </h4>
                {df_html}
                <h4>可登陆信息门户-预算管理系统查看预算详细信息,如有问题请联系财务计划处 联系电话:000012 任00    </h4>
                <h4>{dept_name}</h4>
                <h4>{new_time}</h4>
            </div>


            <hr>
            <p style="text-align: center">
            </p>
        </div>
        </body>
        """.format(yesterday=yesterday, teacher_name=teacher_name, new_time=new_time, dept_name=dept_name,
                   df_html=df_html)
html_msg = "<html>" + head + body + "</html>"
html_msg = html_msg.replace('\n', '').encode("utf-8")
_user = '1******5@qq.com'
_pwd = 'wg******orbafe'
_to = 'zj******16@163.com'
msg = MIMEMultipart()
msg["Subject"] = '预算下达邮件通知'
msg["From"] = _user
msg["To"] = _to
part = MIMEText(html_msg, 'html', 'utf-8')
msg.attach(part)
s = smtplib.SMTP("smtp.qq.com", timeout=30)
s.login(_user, _pwd)
s.sendmail(_user, _to, msg.as_string())
s.close()
print('发送成功')

效果如下:

'''
纯文本发送
构造邮件内容的MIMEText类有三个参数,第一个参数为文本内容,第二个参数‘plain’设置文本格式,第三个参数设置编码格式
'''
## 导入模块
import random
from email.mime.multipart import MIMEMultipart
from Models.models import *
import smtplib
# email 用于构建邮件内容
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
import pandas as pd
from email.mime.application import MIMEApplication
# 构建邮件头
from email.header import Header
from Settings.config import ServerIp


# mail_host = "smtp.qq.com" #SMTP服务器地址
# mail_sender = '1252****5@qq.com'
# mail_passwd = 'wgxncm***corbafe'

mail_list = [        # 发送列表
    {
    'mail_host' : "smtp.qq.com", #SMTP服务器地址
    'mail_sender' : '125287***5@qq.com',
    'mail_passwd' : 'wgxncm***corbafe'
    },

]

def get_mail_config():  # 获取一个发送账号

    b = random.choices(mail_list,k=1)[0]
    return b.get('mail_host'), b.get('mail_sender'), b.get('mail_passwd')

def send_email_text(code=123, to=None):  # 发送文本

    mail_host, mail_sender, mail_passwd = get_mail_config()

    ## 构造邮件内容
    content = f"您正在修改密码, 验证码为{code},验证码有效时长5分钟"
    msg = MIMEText(content, 'plain', 'utf-8')
    msg["Subject"] = "酒店管理密码修改"
    msg["From"] = mail_sender  # 发送人
    msg["To"] = to  # 接收人
    try:

        ## 发送邮件
        s = smtplib.SMTP() #实例化对象
        s.connect(mail_host, 25) #连接163邮箱服务器,端口号为25
        s.login(mail_sender, mail_passwd) #登录邮箱
        s.sendmail(mail_sender, [to], msg.as_string())
        s.quit()

        return {'code': '0', 'msg': '邮件发送成功!'}

    except Exception as e:


        return {'code': 500, 'msg': f'邮件发送失败, 方法为send_email_text2, 报错信息为{e}'}



def send_email_text3(content=None,title=None, to=None, imageFile=None):   # 专题图片邮件

    mail_host, mail_sender, mail_passwd = get_mail_config()

    head = \
        """
                <head>
                    <meta charset="utf-8">
                </head>
                """
    body = \
        f"""
                <body>
                    {content}
                <hr>
                <div class="content">
                    <img src="{imageFile}"/>
                </div>
                </body>
                """
    html_msg = "<html>" + head + body + "</html>"
    html_msg = html_msg.replace('\n', '').encode("utf-8")

    msg = MIMEMultipart()
    msg["Subject"] = title
    msg["From"] = mail_sender
    msg["To"] = to

    try:
        part = MIMEText(html_msg, 'html', 'utf-8')
        msg.attach(part)
        s = smtplib.SMTP("smtp.qq.com", timeout=30)
        s.login(mail_sender, mail_passwd)
        s.sendmail(mail_sender, to, msg.as_string())
        s.close()
        print('发送成功')

        return {'code': '0', 'msg': '邮件发送成功!'}

    except smtplib.SMTPException as e:

        return {'code': 500, 'msg': f'邮件发送失败, 方法为send_email_text2, 报错信息为{e}'}


def send_email_text4(
        content='',
        title='', to=None, datalist=None):

    mail_host, mail_sender, mail_passwd = get_mail_config()

    columns = ['客户名称', '公司名称', '职位', '客户类型', '会员等级']
    filter_merge_data = pd.DataFrame(datalist, columns=columns)
    df_html = filter_merge_data.to_html(escape=False)  # DataFrame数据转化为HTML表格形式
    head = \
        """
                <head>
                    <meta charset="utf-8">
                    <STYLE TYPE="text/css" MEDIA=screen>
                        table.dataframe {
                            border-collapse: collapse;
                            border: 2px solid #a19da2;
                            /*居中显示整个表格*/
                            margin: auto;
                        }
                        table.dataframe thead {
                            border: 2px solid #91c6e1;
                            background: #f1f1f1;
                            padding: 10px 10px 10px 10px;
                            color: #333333;
                        }
                        table.dataframe tbody {
                            border: 2px solid #91c6e1;
                            padding: 10px 10px 10px 10px;
                        }
                        table.dataframe tr {
                        }
                        table.dataframe th {
                            vertical-align: top;
                            font-size: 14px;
                            padding: 10px 10px 10px 10px;
                            color: #105de3;
                            font-family: arial;
                            text-align: center;
                        }
                        table.dataframe td {
                            text-align: center;
                            padding: 10px 10px 10px 10px;
                        }
                        body {
                            font-family: 宋体;
                        }
                        h1 {
                            color: #5db446
                        }
                        div.header h2 {
                            color: #0002e3;
                            font-family: 黑体;
                        }
                        div.content h2 {
                            text-align: center;
                            font-size: 28px;
                            text-shadow: 2px 2px 1px #de4040;
                            color: #fff;
                            font-weight: bold;
                            background-color: #008eb7;
                            line-height: 1.5;
                            margin: 20px 0;
                            box-shadow: 10px 10px 5px #888888;
                            border-radius: 5px;
                        }
                        h3 {
                            font-size: 22px;
                            background-color: rgba(0, 2, 227, 0.71);
                            text-shadow: 2px 2px 1px #de4040;
                            color: rgba(239, 241, 234, 0.99);
                            line-height: 1.5;
                        }
                        h4 {
                            color: #e10092;
                            font-family: 楷体;
                            font-size: 20px;
                            text-align: center;
                        }
                        td img {
                            /*width: 60px;*/
                            max-width: 300px;
                            max-height: 300px;
                        }
                    </STYLE>
                </head>
                """
    body = \
        f"""
                <body>
                <div class="content">

                    <div>
                        {content}:
                        {df_html}
                    </div>
                    <hr>
                    <p style="text-align: center">
                    </p>
                </div>
                </body>
                """
    html_msg = "<html>" + head + body + "</html>"
    html_msg = html_msg.replace('\n', '').encode("utf-8")
    msg = MIMEMultipart()
    msg["Subject"] = title
    msg["From"] = mail_sender
    msg["To"] = to
    part = MIMEText(html_msg, 'html', 'utf-8')
    msg.attach(part)
    s = smtplib.SMTP("smtp.qq.com", timeout=30)
    s.login(mail_sender, mail_passwd)
    s.sendmail(mail_sender, to, msg.as_string())
    s.close()
    print('发送成功')

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值