Python实现smtp服务发送带附件的邮件

来了哈: 

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 使用smtp服务发带附件的邮件

import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import os


if __name__ == '__main__':
    host = "smtp.*****.com"
    port = 25
    mail_user = "******@*****.com"
    mail_pass = "******"
    toaddrs = ["614027762@qq.com"]

    # 附件
    textApart = MIMEText('这是有附件的')
    imageFile = os.path.abspath('../res/1.png')
    imageApart = MIMEImage(open(imageFile, 'rb').read(), imageFile.split('.')[-1])
    imageApart.add_header('Content-Disposition', 'attachment', filename="1.png")

    pdfFile = os.path.abspath('../res/分析方法.pdf')
    pdfApart = MIMEApplication(open(pdfFile, 'rb').read())
    pdfApart.add_header('Content-Disposition', 'attachment', filename="方法.pdf")

    zipFile = os.path.abspath('../res/do.zip')
    zipApart = MIMEApplication(open(zipFile, 'rb').read())
    zipApart.add_header('Content-Disposition', 'attachment', filename="do.zip")

    message = MIMEMultipart()
    message.attach(textApart)
    message.attach(imageApart)
    message.attach(pdfApart)
    message.attach(zipApart)
    message['From'] = Header("明", 'utf-8')
    message['To'] = Header("明; 波", 'utf-8')
    subject = '【报告测试进行中】'
    message['Subject'] = Header(subject, 'utf-8')

    try:
        server = smtplib.SMTP()
        server.connect(host, port)  # 链接服务器;25 为 SMTP 端口号
        server.login(mail_user, mail_pass)
        server.sendmail(mail_user, toaddrs, message.as_string())
        print("success")
        server.quit()
    except smtplib.SMTPException as e:
        print("error:", e)

完了哈。*号部分改成你自己的。附件文件自己创造。

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值