python 发送邮件和附件

#!/usr/bin/python3
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart


# 第三方 SMTP 服务
# mail_host = "hwsmtp.qiye.163.com"  # 设置服务器
mail_host = "smtp.163.com"  # 设置服务器

mail_user = "*@163.com"  # 用户名
mail_pass = "*"  # 口令

sender = '*@163.com'
receivers = '*qq.com,*@*.cn' # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

message =MIMEMultipart();#  发送待附件的邮件
#message=MIMEText('Python 邮件发送测试...', 'plain', 'utf-8')   #发送普通邮件不带附件
#message['From'] = Header("菜鸟教程", 'utf-8')
#message['To'] = Header("测试", 'utf-8')
#报错原因是因为“发件人和收件人参数没有进行定义  虽然已经设置了sender和receivers但是还要设置from和to 发送实际接收是message['to'] 中的邮箱
message['from'] = sender
message['to'] = receivers
message['Cc'] = '*@qq.com'
subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')

# 构造附件1,传送当前目录下的 test.txt 文件
att1 = MIMEText(open('d:/jquery-2.2.0.min.js', 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写,写什么名字,邮件中显示什么名字
att1["Content-Disposition"] = 'attachment; filename="jquery-2.2.0.min.js"'
message.attach(att1)

# 构造附件2,传送当前目录下的 runoob.txt 文件
att2 = MIMEText(open('d:\createMvnWeb.bat', 'rb').read(), 'base64', 'utf-8')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="createMvnWeb.bat"'
message.attach(att2)

try:
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host, 25)  # 25 为 SMTP 端口号
    smtpObj.login(mail_user, mail_pass)
    smtpObj.sendmail(sender, receivers, message.as_string())
    print("邮件发送成功")
except smtplib.SMTPException as e:
    print("Error: 无法发送邮件"+e)

猜你喜欢

转载自blog.csdn.net/ctllin/article/details/78959669