使用python发送复杂邮件

类名 SendEmail.py

# !/usr/bin/python
# -*- coding: UTF-8 -*-
# 遇到没有执行权限,使用 chmod a+x SendEmail.py
 
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.utils import formataddr
from email.mime.image import MIMEImage
from email.header import Header
 
username = 'xxxxxxxxxxxxxxxxxxx'      # 发件人邮箱账号
password = 'xxxxxxxxxxxxxxxx'         # 发件人邮箱密码(授权码)
send_to = 'xxxxxxxxxxxxxxxxx'         # 收件人邮箱账号,我这边发送给自己
def mail():
    ret = True
    msg = MIMEMultipart()
    msg['From'] = formataddr(["liyang", username])
    msg['To'] =  formataddr(["anonymous", send_to])
    subject = 'Python SMTP 邮件测试'
    msg['Subject'] = Header(subject, 'utf-8')

    # 正文部分
    content = MIMEMultipart() # 如果仅发送一段文本,而不是html,使用 MIMEText('content','plain','utf-8') 即可
    mail_msg = """
    <p>Python发送复杂邮件测试...</p>
    <p><a href="http://www.github.com">github仓库地址</a></p>
    <p>图片演示:</p>
    <p><img src="cid:image_github"></p>
    """
    content.attach(MIMEText(mail_msg, 'html', 'utf-8'))
    # 指定图片为当前目录
    fp = open('github.jpg', 'rb')
    msgImage = MIMEImage(fp.read())
    fp.close()
    msgImage.add_header('Content-ID', '<image_github>')

    # markdown附件
    markdown = MIMEText(open('README.md', 'rb').read(), 'base64', 'utf-8')
    markdown["Content-Type"] = 'application/octet-stream'
    markdown.add_header('Content-Disposition', 'attachment', filename = 'README')

    # 照片附件
    with open('car.png','rb') as fp:
        picture = MIMEImage(fp.read())
        #与txt文件设置相似
        picture['Content-Type'] = 'application/octet-stream'
        picture['Content-Disposition'] = 'attachment; filename = "car.png"'

    # 加入到msg
    msg.attach(content)
    msg.attach(msgImage)
    msg.attach(markdown)
    msg.attach(picture)

    try:
        server = smtplib.SMTP_SSL("smtphz.qiye.163.com", 465)    # 发件人邮箱中的SMTP服务器,网易邮箱的端口是465
        server.login(username, password)                         # 括号中对应的是发件人邮箱账号、邮箱密码
        server.sendmail(username, [send_to,], msg.as_string())   # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
        server.quit()                                            # 关闭连接
    except Exception:                                            # 如果 try 中的语句没有执行,则会执行下面的 ret=False
        ret = False
    return ret
 
ret = mail()
if ret:
    print("邮件发送成功")
else:
    print("邮件发送失败")
python3 SendEmail.py

参考资料:
简单三步,用 Python 发邮件
Python SMTP发送邮件

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值