Python发送文字邮件,附件

本文介绍如何利用Python编程语言发送包含文字内容和附件的电子邮件。内容涵盖邮件的创建、附件的添加以及发送过程。
摘要由CSDN通过智能技术生成

发送文字 

import smtplib
from email.mime.text import MIMEText
from email.header import Header

#发送邮件服务器
smtpserver = 'smtp.126.com'
#发送邮箱用户/密码
user = 'user@126.com'
passw = 'XXXXX'

#发送邮箱
sender = 'sender@126.com'
#接收邮箱 这里也可以数组传多个邮箱
receiver = 'get@126.com'
#邮件主题
subject = 'Python Mail Test'
#编写html正文
#msg = MIMEText('hello,send by Python.....','plain','utf-8')
msg = MIMEText('<html><h1>你好,我是来自python的邮件</h1></html>','html','utf-8')
msg['Subject'] = Header(subject,'utf-8')


#连接发送邮件
smtpTest = smtplib.SMTP()
smtpTest.connect(smtpserver,25)
smtpTest.login(user,passw)
#这里第二个邮件是发送给收件人,但是自己测试被126报告544错误,说是垃圾邮件,所以发自己玩。。。
smtpTest.sendmail(sender,sender,msg.as_string())
smtpTest.close()

发送附件

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header

#发送邮件服务器
smtpserver = 'smtp.126.com'
#发送邮箱用户/密码
user = '123@126.com'
passw = '123'

#发送邮箱
sender = '123@126.com'
#接收邮箱
receiver = '123@126.com'
#邮件主题
subject = 'Python Mail Test'

#附件
sendfile = open('E:\\pythonWorkSpace\\com\\sola\\htmlrunner\\2019-03-08 17_51_10result.html','rb').read()

att = MIMEText(sendfile,'base64','utf-8')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename = log.html'

msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = subject
msgRoot.attach(att)


#连接发送邮件
smtpTest = smtplib.SMTP()
smtpTest.connect(smtpserver,25)
smtpTest.login(user,passw)
#这里第二个邮件是发送给收件人,但是自己测试被126报告544错误,说是垃圾邮件,所以发自己玩。。。
smtpTest.sendmail(sender,sender,msgRoot.as_string())
smtpTest.close()

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值