python之发送邮件

在学习怎么使用python发送邮件之前,首先要知道什么是授权码。

授权码是用于登录第三方邮件客户端的专用密码

网易邮箱获取授权码的方式

qq邮箱获取授权码的方式

 

接下来我们看怎么使用python自动发送邮件

import smtplib
from email.mime.text import MIMEText

mailserver = "smtp.163.com" #邮箱服务器地址
username_send = 'test@163.com' #邮箱用户名
password = 'XXXX' #邮箱密码:需要使用授权码
username_recv = 'test@qq.com' #收件人,多个收件人用逗号隔开
mail = MIMEText('这是发用的邮件内容')
mail['Subject'] = '这是邮件主题'
mail['From'] = username_send #发件人
mail['To'] = username_recv #收件人;[]里的三个是固定写法,别问为什么,我只是代码的搬运工
smtp = smtplib.SMTP(mailserver,port=25) # 连接邮箱服务器,smtp的端口号是25
# smtp=smtplib.SMTP_SSL('smtp.qq.com',port=465) #QQ邮箱的服务器和端口号
smtp.login(username_send,password) #登录邮箱
smtp.sendmail(username_send,username_recv,mail.as_string())# 参数分别是发送者,接收者,第三个是把上面的发送邮件的内容变成字符串
smtp.quit() # 发送完毕后退出smtp
print ('success')

发送后的邮件

升级一下邮件内容,我们发送一封带有附件的邮件

import smtplib
import base64
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

mailserver = "smtp.163.com" #邮箱服务器地址
username_send = 'mapeipei04265@163.com' #邮箱用户名
password = 'las0312e' #邮箱密码:需要使用授权码
username_recv = '272932709@qq.com' #收件人,多个收件人用逗号隔开
mail = MIMEMultipart()
# file = r'E:\testpy\python-mpp\day8\练习\sendmail.py'
# att = MIMEText(open(file,encoding='utf-8').read()) #这个只可以发送py或者txt附件,复杂一点的就会报错
file=r'E:\testpy\python-mpp\day7\作业\data\mpp.xls'
att = MIMEText(open(file, 'rb').read(),"base64", "utf-8") #这个可以发送复杂的附件,比如附件为表格
att["Content-Type"] = 'application/octet-stream'

#这行是把附件的格式进行一些处理,不知道为啥要这么写,但是如果不写接收到的附件已经不是表格样式了
new_file='=?utf-8?b?' + base64.b64encode(file.encode()).decode() + '?='

att["Content-Disposition"] = 'attachment; filename="%s"'%new_file
mail.attach(att)
mail.attach(MIMEText('这是一封带有附件的邮件正文内容,假装很长'))#邮件正文的内容
mail['Subject'] = '这是邮件主题'
mail['From'] = username_send #发件人
mail['To'] = username_recv #收件人;[]里的三个是固定写法,别问为什么,我只是代码的搬运工
smtp = smtplib.SMTP(mailserver,port=25) # 连接邮箱服务器,smtp的端口号是25
# smtp=smtplib.SMTP_SSL('smtp.qq.com',port=465) #QQ邮箱的服务器和端口号
smtp.login(username_send,password) #登录邮箱
smtp.sendmail(username_send,username_recv,mail.as_string())# 参数分别是发送者,接收者,第三个是把上面的发送邮件的内容变成字符串
smtp.quit() # 发送完毕后退出smtp
print ('success')

发送后的邮件

 最后放上一个老师封装好的发送邮件的函数,使用的时候直接调用即可

import smtplib,os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import base64
class SendMail(object):
def __init__(self,username,passwd,recv,title,content,
file=None,ssl=False,
email_host='smtp.qq.com',port=25,ssl_port=465):
'''
:param username: 用户名
:param passwd: 密码
:param recv: 收件人,多个要传list ['a@qq.com','b@qq.com]
:param title: 邮件标题
:param content: 邮件正文
:param file: 附件路径,如果不在当前目录下,要写绝对路径,默认没有附件
:param ssl: 是否安全链接,默认为普通
:param email_host: smtp服务器地址,默认为163服务器
:param port: 非安全链接端口,默认为25
:param ssl_port: 安全链接端口,默认为465
'''
self.username = username #用户名
self.passwd = passwd #密码
self.recv = recv #收件人,多个要传list ['a@qq.com','b@qq.com]
self.title = title #邮件标题
self.content = content #邮件正文
self.file = file #附件路径,如果不在当前目录下,要写绝对路径
self.email_host = email_host #smtp服务器地址
self.port = port #普通端口
self.ssl = ssl #是否安全链接
self.ssl_port = ssl_port #安全链接端口
def send_mail(self):
msg = MIMEMultipart()
#发送内容的对象
if self.file:#处理附件的
file_name = os.path.split(self.file)[-1]#只取文件名,不取路径
try:
f = open(self.file, 'rb').read()
except Exception as e:
raise Exception('附件打不开!!!!')
else:
att = MIMEText(f,"base64", "utf-8")
att["Content-Type"] = 'application/octet-stream'
#base64.b64encode(file_name.encode()).decode()
new_file_name='=?utf-8?b?' + base64.b64encode(file_name.encode()).decode() + '?='
#这里是处理文件名为中文名的,必须这么写
att["Content-Disposition"] = 'attachment; filename="%s"'%(new_file_name)
msg.attach(att)
msg.attach(MIMEText(self.content))#邮件正文的内容
msg['Subject'] = self.title # 邮件主题
msg['From'] = self.username # 发送者账号
msg['To'] = ','.join(self.recv) # 接收者账号列表
if self.ssl:
self.smtp = smtplib.SMTP_SSL(self.email_host,port=self.ssl_port)
else:
self.smtp = smtplib.SMTP(self.email_host,port=self.port)
#发送邮件服务器的对象
self.smtp.login(self.username,self.passwd)
try:
self.smtp.sendmail(self.username,self.recv,msg.as_string())
pass
except Exception as e:
print('出错了。。',e)
else:
print('发送成功!')
self.smtp.quit()


if __name__ == '__main__':
m = SendMail(
username='test@qq.com',
passwd='xxxxxx',
recv=['test001@163.com','test002@qq.com'],
title='发送邮件20180205',
content='测试发送邮件,qq发件,接收方一个是163邮箱,另一个是qq邮箱。20180205',
file=r'E:\testpy\python-mpp\day7\作业\data\mpp.xls',
ssl=True,
)
m.send_mail()



原文地址:https://www.cnblogs.com/mpp0905/p/8419869.html