Python发送QQ邮件

普通邮件

使用Python的smtplib可以发送QQ邮件,代码如下

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


sender = '111@qq.com'  # 发送邮箱
receivers = ['222@qq.com']  # 接收邮箱
auth_code = "abc"  # 授权码

message = MIMEText('Python发送邮件', 'plain', 'utf-8')
message['From'] = Header("Sender<%s>" % sender)  # 发送者
message['To'] = Header("Receiver<%s>" % receivers[0])  # 接收者

subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')


try:
    server = smtplib.SMTP_SSL('smtp.qq.com', 465)
    server.login(sender, auth_code)
    server.sendmail(sender, receivers, message.as_string())
    print("邮件发送成功")
    server.close()
except smtplib.SMTPException:
    print("Error: 无法发送邮件")

发送邮件服务器要用465端口,否则如下错误:
login的密码不是邮箱登录密码,而是授权码,需要在QQ邮箱设置-账号里获取。
1
否则会报如下错误:

SMTPServerDisconnected: Connection unexpectedly closed
SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1002)

发送消息的From和To要用标准格式,否则报错:

SMTPDataError: (550, b'The "From" header is missing or invalid. Please follow RFC5322, RFC2047, RFC822 standard protocol. https://service.mail.qq.com/detail/124/995.')

1

带附件邮件

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


def send_email(filename):

    sender = 'xxxxx@qq.com'  # 发送邮箱
    receivers = ['xx@xx.com']  # 接收邮箱
    auth_code = "auth code"  # 授权码

    message = MIMEMultipart()
    message['From'] = email.utils.formataddr(('发送者', sender))  # 发送者
    message['To'] = email.utils.formataddr(('收件人', receivers[0]))  # 接收者

    message['Subject'] = Header(filename, 'utf-8')

    content = MIMEText(filename)
    message.attach(content)

    # 附件
    excel = MIMEApplication(open(filename, 'rb').read())  # 打开Excel,读取Excel文件
    excel["Content-Type"] = 'application/octet-stream'  # 设置内容类型
    excel.add_header('Content-Disposition', 'attachment', filename=filename)
    message.attach(excel)

    try:
        server = smtplib.SMTP_SSL('smtp.qq.com', 465)
        server.login(sender, auth_code)
        server.sendmail(sender, receivers, message.as_string())
        server.set_debuglevel(True)
        print("邮件发送成功")
        server.close()
    except smtplib.SMTPException:
        print("Error: 无法发送邮件")

参考

https://wx.mail.qq.com/list/readtemplate?name=app_intro.html#/agreement/authorizationCode
https://help.mail.qq.com/detail/0/994
https://docs.python.org/zh-cn/3/library/netdata.html
https://docs.python.org/zh-cn/3/library/smtplib.html

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小龙在山东

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值