SMTP(Simple Mail Transfer Protocol)简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式,在Python中,提供了smtp发送电子邮件,模块smtp对smtp协议进行了简单的封装,在这里通过QQ邮箱发送邮件。
一,首先,邮件的发送需要哪些内容? 思路如下:
1. 发送邮箱服务器,这里的QQ SMTP:smtp.qq.com,端口port:465
2. 发件人用户名与密码:mail_user,mail_pass
3. 发件人地址:xxx@qq.com
4. 接收人的地址列表:['xxx@qq.com']
5. 邮件正文文本内容,文本格式,文本编码,MIMEText()
6. 邮件发送者,message['from']
7. 邮件接收者,message['to']
二,使用Python发送邮件示例脚本
1. 邮件发送脚本示例01
import smtplib
from email.mime.text import MIMEText
from email.header import Header
mail_host = 'smtp.qq.com'
mail_user = 'xxx@qq.com'
mail_pass = 'password'
sender = 'xxx@qq.com'
receivers = ['xxx@qq.com']
message = MIMEText('Python邮件发送测试!--邮件正文内容!', 'plain', 'utf-8')
message['from'] = Header("菜鸟教程!--邮件发送人!", 'utf-8')
message['to'] = Header('邮件发送测试! --邮件收件人!', 'utf-8')
subject = 'Python SMTP 邮件测试! --邮件主题!'
message['subject'] = Header(subject, 'utf-8')
try:
smtpObj = smtplib.SMTP_SSL(mail_host, 465) #重点!这里是ssl
smtpObj.login(mail_user, mail_pass)
smtpObj.sendmail(sender, receivers, message.as_string())
print("Python邮件测试发送成功!")
except smtplib.SMTPException:
print("Error: Python邮件发送失败!")
2. 邮件发送示例02
import smtplib
from email.utils import formatdate
from email.header import Header
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# smtplib用来发送邮件
# email用来构造邮件内容
username = "xx" # 发件人用户名
password = "xxx" #发件人密码
smtp_addr = "smtp.qq.com" #发件人邮件服务器地址
from_addr = username + "@qq.com" #发件人邮箱
to_addr = ['xxx@163.com', 'yyy@qq.com'] #收件人地址列表
def message_template01(): #创建邮件内容的模板01
mail_msg = """
Python邮件发送测试!
这是狗东链接
"""
message = MIMEText(mail_msg, 'html', 'utf-8')
message['Subject'] = Header('Python SMTP邮件测试!', 'utf-8')
message['From'] = Header(username, 'utf-8')
message['To'] = Header('; '.join(to_addr), 'utf-8')
message['Date'] = formatdate(localtime=True)
return message
def send_mail():
message = message_template01()
try:
smtpObj = smtplib.SMTP_SSL(host=smtp_addr, port=465) #SSL,且必须带有参数host
# smtpObj = smtplib.SMTP_SSL()
# smtpObj.connect(host=smtp_addr, port=465)
smtpObj.login(username, password)
smtpObj.sendmail(from_addr, to_addr, message.as_string())
smtpObj.quit()
print("测试邮件发送成功!")
except smtplib.SMTPException as e:
print(repr(e)) # repr()函数是将对象转化为可供解释器读取的形式!
print("Error: 无法发送邮件!")
if __name__ == '__main__':
send_mail()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)