python模块----yagmail模块smtplib模块 (电子邮件)
Posted du-z
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python模块----yagmail模块smtplib模块 (电子邮件)相关的知识,希望对你有一定的参考价值。
yagmail模块
python标准库发送电子邮件的模块比较复杂,so,许多开源的库提供了更加易用的接口来发送电子邮件,其中yagmail是使用比较广泛的开源项目,yagmail底层依然使用smtplib和email模块,但是提供了更好的接口,并具有更好的易读性。
第一步:安装yagmail模块
pip install yagmail
第二步:发邮件
#导入yagmail模块
import yagmail
#1.实例化出来一个yagmail对象
yag = yagmail.SMTP(user=‘xxxx@163.com‘,password=‘xxxx‘,host=‘smtp.163.com‘)
##(可选)编写内容(其实contents就是一个变量)
contents=‘hello world!!!‘
#2.发送邮件操作
yag.send(to=‘接收端@163.com‘,subject=None,contents=contents)
##3.断开连接
yag.close()
拓展1:发送多个用户
yag.send(to=[‘xx1.@163.com‘,‘xx2.@162.com‘],subject=subject,contents)
拓展2:发送附件
contents=[‘邮件内容‘,‘附件路径‘]
smtplib模块
python发送邮件(不带附件)
import smtplib
from email.mime.text import MIMEText
from email.header import Header
sender = ‘xxxx@163.com‘
receiver = ‘xxxxxx@126.com‘
subject = ‘报警‘
username = ‘xxxx@163.com‘
password = ‘xxxx‘
msg = MIMEText(strs, ‘plain‘, ‘utf-8‘)
msg[‘Subject‘] = Header(subject, ‘utf-8‘)
msg[‘From‘] = ‘Tim<xxxx@163.com>‘
msg[‘To‘] = "xxxxxx@126.com"
smtp = smtplib.SMTP()
smtp.connect(‘smtp.163.com‘)
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()
python发送邮件(带附件)
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
USER = ‘xxxx@163.com‘
PASSWORD = ‘xxxxxx‘
# 如名字所示: Multipart就是多个部分
msg = MIMEMultipart()
HOST = ‘smtp.163.com‘
msg[‘subject‘] = ‘test email from python‘
msg[‘to‘] = ‘xxxx@126.com‘
msg[‘from‘] = ‘xxxxxx@163.com‘
text = MIMEText(‘我是纯文本‘)
msg.attach(text)
#添加附件1
xlsxpart = MIMEApplication(open(‘test1.xlsx‘, ‘rb‘).read())
xlsxpart.add_header(‘Content-Disposition‘, ‘attachment‘, filename=‘test1.xlsx‘)
msg.attach(xlsxpart)
#添加附件2
xlsxpart2 = MIMEApplication(open(‘test2.xlsx‘, ‘rb‘).read())
xlsxpart2.add_header(‘Content-Disposition‘, ‘attachment‘, filename=‘test2.xlsx‘)
msg.attach(xlsxpart2)
#开始发送邮件
client = smtplib.SMTP()
client.connect(HOST)
client.login(USER, PASSWORD)
client.sendmail(‘xxxxx@163.com‘, [‘xxxx@126.com‘], msg.as_string())
client.quit()
print(‘发送成功........‘)
以上是关于python模块----yagmail模块smtplib模块 (电子邮件)的主要内容,如果未能解决你的问题,请参考以下文章
python模块----yagmail模块smtplib模块 (电子邮件)