python模块----yagmail模块、smtplib模块 (电子邮件)

singer 2020-05-06

yagmail模块

python标准库发送电子邮件的模块比较复杂,so,许多开源的库提供了更加易用的接口来发送电子邮件,其中yagmail是使用比较广泛的开源项目,yagmail底层依然使用smtplib和email模块,但是提供了更好的接口,并具有更好的易读性。

第一步:安装yagmail模块

pip install yagmail

第二步:发邮件

#导入yagmail模块
import yagmail

#1.实例化出来一个yagmail对象
yag = yagmail.SMTP(user=‘‘,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=[‘‘,‘‘],subject=subject,contents)

拓展2:发送附件

contents=[‘邮件内容‘,‘附件路径‘]

smtplib模块

python发送邮件(不带附件)

import smtplib
from email.mime.text import MIMEText
from email.header import Header
sender = ‘‘
receiver = ‘‘
subject = ‘报警‘
username = ‘‘
password = ‘xxxx‘
msg = MIMEText(strs, ‘plain‘, ‘utf-8‘)
msg[‘Subject‘] = Header(subject, ‘utf-8‘)
msg[‘From‘] = ‘Tim<>‘
msg[‘To‘] = ""
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 = ‘‘
PASSWORD = ‘xxxxxx‘
# 如名字所示: Multipart就是多个部分
msg = MIMEMultipart()
HOST = ‘smtp.163.com‘
msg[‘subject‘] = ‘test email from python‘
msg[‘to‘] = ‘‘
msg[‘from‘] = ‘‘
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(‘‘, [‘‘], msg.as_string())
client.quit()
print(‘发送成功........‘)

相关推荐