使用python发送邮件

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

使用python发送邮件_第1张图片

之后就可以发邮箱啦:

文本邮件

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()

如图:

使用python发送邮件_第2张图片

附件邮件

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 = ['*****[email protected]', '*****[email protected]'] # 收件人

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)  # 打印错误

如图:

使用python发送邮件_第3张图片

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 = \
"""
        
            
            
        
        """
body = \
"""
        
        

关于下达{yesterday}年各部门/专项经费预算指标的通知


{teacher_name}老师 您好:

学校党委会已批准{yesterday}年各部门/专项预算方案,财务计划处已将预算指标导入ARP系统,请各位负责人及时查看,明细如下:

{df_html}

可登陆信息门户-预算管理系统查看预算详细信息,如有问题请联系财务计划处 联系电话:000012 任00

{dept_name}

{new_time}


""".format(yesterday=yesterday, teacher_name=teacher_name, new_time=new_time, dept_name=dept_name, df_html=df_html) html_msg = "" + head + body + "" html_msg = html_msg.replace('\n', '').encode("utf-8") _user = '1******[email protected]' _pwd = 'wg******orbafe' _to = 'zj******[email protected]' 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('发送成功')

效果如下:

使用python发送邮件_第4张图片

你可能感兴趣的:(python)