python学习-发送邮件(smtp)

1. 之前学习过用调用第三方模块yagmail来发送邮件,今天又学习了下,用python自带smtplib来发送邮件

前言:

SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。

python的smtplib提供了一种很方便的途径发送电子邮件。它对smtp协议进行了简单的封装。

参考代码:

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

# 第三方 SMTP 服务
mail_host = "smtp.qq.com"  # 设置服务器
mail_user = '364645665454@qq.com'  # 用户名
mail_pass = "5546654"  # 口令

sender = 45353453@qq.com'
receivers = ['dfgd@163.com', 'gfghdgdgd@126.com']  # 接收邮件,可设置为你的163邮箱或者其他邮箱

message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8')
message['From'] = Header(sender, 'utf-8')
message['To'] = Header(receivers, 'utf-8')

subject = '我的第一封邮件'
message['Subject'] = Header(subject, 'utf-8')

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:
    print("Error: 无法发送邮件")

 

 

 

使用Python发送HTML格式的邮件

Python发送HTML格式的邮件与发送纯文本消息的邮件不同之处就是将MIMEText中_subtype设置为html。具体代码如下:

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

# 第三方 SMTP 服务
mail_host = "smtp.qq.com"  # 设置服务器
mail_user = '364645665454@qq.com'  # 用户名
mail_pass = "5546654"  # 口令

sender = 45353453@qq.com'
receivers = ['dfgd@163.com', 'gfghdgdgd@126.com']  # 接收邮件,可设置为你的163邮箱或者其他邮箱
mail_msg = """
<p>Python 邮件发送测试...</p>
<p>这是我的第一次操作</p>
<p><a href="http://www.runoob.com">这是一个链接</a></p>
"""
message = MIMEText(mail_msg, 'html', 'utf-8')
message['From'] = Header(sender, 'utf-8')
message['To'] = Header(','.join(receivers))

subject = '我的第一封邮件'
message['Subject'] = Header(subject, 'utf-8')

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:
    print("Error: 无法发送邮件")

 参考链接:https://www.runoob.com/python3/python3-smtp.html

posted @ 2020-10-18 17:24  Penny悦  阅读(171)  评论(0编辑  收藏  举报