python语言使用smtp发送带附件的邮件

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
from email.mime.image import MIMEImage
def send_mail(self):
    mail_host = "smtp.qq.com"  # SMTP服务器地址
    mail_sender = "******@qq.com"  # 发送人账号
    mail_receiver ="*****@qq.com"  #接收人账号  

    msg = MIMEMultipart()
    msg["Subject"] = "带有附件的邮件"
    msg["From"] = mail_sender  # 发送人
    msg["To"] = mail_receiver  # 接收人账号

    # 邮件正文
    content = '''
    这是一封带有附件的邮件...
    有两个附件
    '''
    msg.attach(MIMEText(content, 'plain', 'utf-8'))

    # 构造附件html文件
    att2 = MIMEText(open('report.html', 'rb').read(), 'base64', 'utf-8')
    att2["Content-Type"] = 'application/octet-stream'
    att2["Content-Disposition"] = 'attachment; filename="report.html"'
    msg.attach(att2)

    ## 发送邮件
    s = smtplib.SMTP('smtp.qq.com')  # 实例化对象
    s.connect('smtp.qq.com', 25)  # 连接163邮箱服务器,端口号为25
    s.login(mail_sender, "gxxinpgfgxnwhiej")  
    # 登录邮箱,gxxinpgfgxnwhiej管理密码,不是登录密码
    s.sendmail(mail_sender, [ mail_receiver], msg.as_string())
    s.quit()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Python是一种高级编程语言,而邮件附件上传是Python在网络编程中的一种重要运用。Python提供了许多库来处理邮件附件上传,其中最常用的是smtplib和email库。 smtplib库提供了连接SMTP服务器发送邮件的方法,包括登录、认证和发送邮件等操作。具体实现的步骤是通过Python程序连接SMTP服务器,构建邮件内容并附加邮件附件,再将邮件发送到指定邮件地址。 而email库则用于构建邮件内容,在构建邮件时非常重要。邮件内容除了正文外,还可以包括附件。要在邮件中添加附件,首先要将附件读入Python程序,使用email库将附件封装为MIMEApplication对象,再将该对象添加到邮件的MIMEMultipart对象中。 例如,以下是一个使用Python发送附件邮件的示例代码: ``` import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication # 邮件发送方、收件方和登录信息 sender = 'example@gmail.com' recipient = 'example@outlook.com' username = 'example@gmail.com' password = 'password' # 邮件主题、正文和附件 subject = '邮件主题' text = '邮件正文' filename = 'file.txt' # 构建邮件内容 msg = MIMEMultipart() msg['From'] = sender msg['To'] = recipient msg['Subject'] = subject # 添加邮件正文 body = MIMEText(text) msg.attach(body) # 添加邮件附件(打开并读取文件,封装为MIMEApplication对象) with open(filename, 'rb') as f: attachment = MIMEApplication(f.read()) attachment.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(attachment) # 连接SMTP服务器并发送邮件 smtp_server = 'smtp.gmail.com' smtp_port = 587 server = smtplib.SMTP(smtp_server, smtp_port) server.starttls() server.login(username, password) server.sendmail(sender, recipient, msg.as_string()) server.quit() ``` 以上代码演示了如何连接SMTP服务器并发送附件邮件。整个过程中需要注意构建邮件时的格式和内容,确保邮件可以正常发送

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值