【python】用SMTP模块发送带附件的邮件

第一篇博客!参考链接

在书上看了用SMTP模块发邮件,试过之后发现并没有什么用。163邮箱开启了SMTP服务后,登陆了发送的时候却被拒收了。

找了前人的资料,发现被过期的教程害死了。

以下代码有效:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
#全部为python内置,不需要安装第三方模块
receivers = ["receivers@163.com"]
sender = "sender@163.com"
mail_pass = "password"
mail_subject = "python发送邮件测试"         # 邮件的标题
mail_context = "这是邮件内容"


msg = MIMEMultipart()
msg["From"] = sender  # 发件人
msg["To"] = ";".join(receivers)  # 收件人
msg["Subject"] = mail_subject   # 邮件标题
# 邮件正文
msg.attach(MIMEText(mail_context, 'plain', 'utf-8'))
#图片附件
#不同的目录下要写全文件路径
with open('test.jpg','rb') as picAtt:
    msgImg = MIMEImage(picAtt.read())
    msgImg.add_header('Content-Disposition', 'attachment', filename='你.jpg')
    #msgImg.add_header('Content-ID', '<0>')
    #msgImg.add_header('X-Attachment-Id', '0')
    msg.attach(msgImg)
# 构造附件
att = MIMEText(open('test.txt', "rb").read(), "base64", "utf-8")
att["Content-Type"] = "application/octet-stream"
# 附件名称为中文时的写法
att.add_header("Content-Disposition", "attachment", filename=("gbk", "", "测试结果.txt"))
# 附件名称非中文时的写法
# att["Content-Disposition"] = 'attachment; filename="test.html")'
msg.attach(att)

try:
    # 启动网易SMTP服务,端口465
    smtpObj = smtplib.SMTP_SSL('smtp.163.com', 465)
    # 登陆账号
    smtpObj.login('sender@163.com', 'your_password')
    # 发送
    smtpObj.sendmail(sender, receivers, msg.as_string())
    print('Success!')
    # 退出登录
    smtpObj.quit()
except smtplib.SMTPException as e:
    print(e)

如果不需要附件,删除附件的代码块就行。

注:密码最好不保存在代码中,而是使用时输入

转载于:https://www.cnblogs.com/to-red/p/9745964.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值