我们需要开启邮箱的IMAP和POP3协议,生成一个授权码,我们使用授权码在我们的刻画段登录邮箱。
一、发送普通文本邮件
import smtplib
from email.mime.text import MIMEText
smtpserver = 'smtp.163.com'
sender = '[email protected]'
receiver = ['[email protected]','[email protected]']
passwd = 'ewwr123'
subject = 'this is test'
with open('/etc/group','r') as file_it:
content = file_it.read()
def create_mail_content():
"""
该函数用于生成邮件消息
:return:
"""
msg = MIMEText(content,'plain','utf-8') #邮件内容与格式编码
msg['From'] = sender #邮件发送者
msg['To'] = ''.join(receiver) #邮件接收者
msg['Subject'] = subject #邮件主题
return msg
def main():
try:
smtpObj = smtplib.SMTP(smtpserver)
smtpObj.login(sender,passwd)
msg = create_mail_content()
smtpObj.sendmail(sender,receiver,msg.as_string())
except Exception as Erorr:
print("Error:邮件发送失败,", Erorr)
else:
print("邮件发送%s成功" % (receiver))
if __name__ == '__main__':
main()
这一段代码我们会使用[email protected]的邮箱给[email protected]和[email protected]发送一份邮件,邮件的主题是'this is test' 邮件的内容使我们/etc/group文件的所有内容。
二、发送html格式的页面邮件
mport smtplib
from email.mime.text import MIMEText
smtpserver = 'smtp.163.com'
sender = '[email protected]'
receiver = ['[email protected]','[email protected]','[email protected]']
passwd = 'w23'
subject = 'this is test email'
def read_file(filename):
with open(filename,'r') as file_it:
content = file_it.read()
return content
def create_email_content():
content = read_file('/root/PycharmProjects/day15/email_info.html')
msg = MIMEText(content,'html','utf-8')
msg['From'] = sender
msg['To'] = ''.join(receiver)
msg['Subject'] = subject
return msg
def send_email():
try:
# 连接STMP服务器
stmObje = smtplib.SMTP(smtpserver)
#邮箱登录
stmObje.login(sender,passwd)
#生成合法的邮件内容
msg = create_email_content()
#邮件发送
stmObje.sendmail(sender,receiver,msg.as_string())
except Exception as Error:
print ('sender email erorr:',Error)
else:
print('sender email success!!')
send_email()
三、发送带有附件的邮件
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
smtpserver = 'smtp.163.com'
sender = '[email protected]'
receiver = ['[email protected]','[email protected]']
passwd = '123'
subject = 'this is test'
def read_file(filename):
"""读取附件文件的内容"""
with open(filename,'rb') as file_it:
file_content = file_it.read()
return file_content
content = '''这是一个测试发送附件的邮件'''
def create_mail_content():
"""
该函数用于生成邮件消息
:return:
"""
msg = MIMEMultipart()
msg.attach(MIMEText(content,'plain','utf-8')) #添加邮件正文内容与,正文格式编码
msg['From'] = sender #邮件发送者
msg['To'] = ''.join(receiver) #邮件接收者
msg['Subject'] = subject #邮件主题
# 构建附件1:
# Base64是网络上最常见的用于传输8Bit字节码的编码方式之一,
# Base64就是一种基于64个可打印字符来表示二进制数据的方法。
file_content = read_file('/etc/passwd')
att1 = MIMEText(file_content,'base64','utf-8')
# Content-Type,内容类型,一般是指网页中存在的Content-Type,
# 用于定义网络文件的类型和网页的编码,决定浏览器将以什么形式、什么编码读取这个文件,
# 这就是经常看到一些Asp网页点击的结果却是下载到的一个文件或一张图片的原因。
# 'application/octet-stream': .* (二进制流,不知道下载文件类型)
att1['Content-type'] = 'application/octet-stram'
# HTTP应答中,Content-Disposition 消息头指示回复的内容该以何种形式展示,
# 是以内联的形式(即网页或者页面的一部分),还是以附件的形式下载并保存到本地
# inline(默认值,表示回复中的消息体会以页面的一部分或者整个页面的形式展示),
# attachment(意味着消息体应该被下载到本地;大多数浏览器会呈现一个“保存为”的对话框,
# 将filename的值预填为下载后的文件
att1['Content-Disposition'] = "attachment; filename='att1_test'"
msg.attach(att1)
return msg
def main():
try:
smtpObj = smtplib.SMTP(smtpserver)
smtpObj.login(sender,passwd)
msg = create_mail_content()
smtpObj.sendmail(sender,receiver,msg.as_string())
except Exception as Erorr:
print("Error:邮件发送失败,", Erorr)
else:
print("邮件发送%s成功" % (receiver))
if __name__ == '__main__':
main()
四、发送内容带有图片的html格式文件的邮件
import smtplib
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
smtpserver = 'smtp.163.com'
sender = '[email protected]'
receiver = ['[email protected]']
passwd = '123'
subject = 'this is test email'
def read_file(filename,mode = 'rb'):
with open(filename,mode) as file_it:
file_data = file_it.read()
return file_data
def create_email_content():
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = ''.join(receiver)
msg['Subject'] = subject
#读取html文本内容
html_content = read_file('/root/PycharmProjects/day15/email_info.html','r')
# 添加html文本消息
msg.attach(MIMEText(html_content,'html','utf-8'))
# 读取图片的内容
image_data = MIMEImage(read_file('/root/PycharmProjects/day15/image01.jpg','rb'))
#add_header(self, _name, _value, **_params)
# 扩展标题设置。名称是要添加的标题字段。 关键字参数可以用来设置
# 通常,参数将被添加为key =“value”
image_data.add_header('Content-ID','<image>')
msg.attach(image_data)
return msg
def send_email():
try:
# 连接STMP服务器
stmObje = smtplib.SMTP(smtpserver)
#邮箱登录
stmObje.login(sender,passwd)
#生成合法的邮件内容
msg = create_email_content()
#邮件发送
stmObje.sendmail(sender,receiver,msg.as_string())
except smtplib.SMTPException as Erorr:
print('send email defualt: ', Erorr)
else:
print('send email success!!!')
send_email()
五、邮件提醒下雨带伞
我们使用爬虫,在中国天气网上将我们所在的城市(以西安为例)的天气信息爬取出来,然后根据天气是否有雨,发送邮件来,提醒我们外出是否带伞。
import smtplib
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import json
from urllib.request import urlopen
from urllib import request
smtpserver = 'smtp.163.com'
sender = '[email protected]'
receiver = '[email protected]'
passwd = 'westos123'
subject = '天气提醒'
def read_file(filename, mode='rb'):
with open(filename, mode) as file_it:
file_data = file_it.read()
return file_data
def create_html_content(temperature,weather):
if '雨' in weather:
remind = '外出需要带伞'
else:
remind = '外出不需要带伞'
content = '''
<h1><center>天气提醒</center></h1>
<center><img src="cid:image" alt="上海鲜花港 - 郁金香" ></center>
<center>temperature:%s</center>
<center>weather:%s</center>
<center>remind:%s</center>
'''%(temperature,weather,remind)
return content
def create_email_content():
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = ''.join(receiver)
msg['Subject'] = subject
#获取天气信息
weatherinfor = get_weather('http://www.weather.com.cn/data/cityinfo/101110101.html')
#json.loads:把字符串编码变成字典,json.dumps()把字符串变为字典格式编码,下面测试案例.
#d = {'name':'fentiao', 'age':10}
# json_d = json.dumps(d)
# json_s = json.loads(json_d)
# print(json_d, type(json_d))
# print(json_s,type(json_s))
weatherinfor = json.loads(weatherinfor)
weather = weatherinfor['weatherinfo']['weather']
temperature = weatherinfor['weatherinfo']['temp1'] +"~"+ weatherinfor['weatherinfo']['temp2']
#生成html文本
html_content = create_html_content(temperature,weather)
# 添加html文本消息
msg.attach(MIMEText(html_content, 'html', 'utf-8'))
# 读取图片的内容
image_data = MIMEImage(read_file('/root/PycharmProjects/day15/image01.jpg', 'rb'))
# add_header(self, _name, _value, **_params)
# 扩展标题设置。名称是要添加的标题字段。 关键字参数可以用来设置
# 通常,参数将被添加为key =“value”
image_data.add_header('Content-ID', '<image>')
msg.attach(image_data)
return msg
def send_email():
try:
# 连接STMP服务器
stmObje = smtplib.SMTP(smtpserver)
# 邮箱登录
stmObje.login(sender, passwd)
# 生成合法的邮件内容
msg = create_email_content()
# 邮件发送
stmObje.sendmail(sender, receiver, msg.as_string())
except smtplib.SMTPException as Erorr:
print('send email defualt: ', Erorr)
else:
print('send email success!!!')
def get_weather(url):
# 生成字典, 指定用户代理为火狐浏览器, 而不是python脚本;
headers = {'User-Agent':'Firefox/23.0'}
# 向url地址发起请求, 返回一个Request对象;
req = request.Request(url,headers=headers)
# 返回一个urlOpen对象, 该对象中包含访问的所有结果, 比如: 网页内容, 网页的状态码(200, 404)
urlObj = urlopen(req)
# 将读取的内容以utf-8编码显示;(中文显示不乱码)
urlContent = urlObj.read().decode('utf-8')
return urlContent
send_email()
我们还是那个面代码已经可以回去城市的天气信息,并且给我们指定的邮箱发邮件提醒,下来我们需要在系统中指定,每天的某个时间去自动运行个脚本文件。
输入命令“crontab -e”,在打开的页面中点击“i”键,进入插入模式,就可以编辑了。
编辑的格式,是“分 时 日 月 周 命令”。当分为*时,表示每分钟执行一次,时为*时,表示每小时执行一次。如果要设置没隔多久执行,则写为“*/数字”,在哪个位置就代表没隔多久执行一次。
每天11点使用python3解释器自动执行该脚本文件。