0x01:由于业务需要用到这个功能,所以顺便简单讲下如何使用python实现。
整个流程如下所示:
登录->写邮件->发送
下面以使用qq邮箱发送为例:
首先需要再qq邮箱里面设置好SMTP这个发件功能以及授权码。
开启SMTP发件功能:
进入qq邮箱,点击账号->选择【POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务】->开启对应的SMTP服务。
设置授权码-16位字符(也就是下面代码中的password):
然后开始编写代码。
1、简单邮件
import smtplib
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
mail_host =('smtp.qq.com')
port =465
send_by = ('[email protected]')
password = ('lsdyxeimzvnebcbh')
send_to = ('[email protected]')
def send_mail(title,content,):
m=MIMEText(content,'plain','utf-8')
m['From']=send_by
m['To']=send_to
m['Subject']=title
#登录
try:
smpt=smtplib.SMTP_SSL(mail_host,port,'utf-8')
smpt.login(send_by,password)
smpt.sendmail(send_by,send_to,m.as_string())
print('success!')
except smtplib.SMTPException as e:
print('Error:',e)
2、各种附件的邮件
这里的话主要是需要区分一下MIME的类型,找到对应的方法,这里可参考http://www.w3school.com.cn/media/media_mimeref.asp
我这里就使用懒人方法,除文本,图片都使用MIMEApplication。
# -*- coding: UTF-8 -*-
import smtplib
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
mail_host =('smtp.qq.com')
port =465
send_by = ('[email protected]')
password = ('lsdyxeimzvnebcbh')
send_to = ('[email protected]')
def send_mail(title,content,):
m=MIMEText(content,'plain','utf-8')
m['From']=send_by
m['To']=send_to
m['Subject']=title
#文本
textApart=MIMEText(content)
# 图片
imageFile = 'D:/test/test.jpg'
imageApart = MIMEImage(open(imageFile, 'rb').read(), imageFile.split('.')[-1])
imageApart.add_header('Content-Disposition', 'attachment', filename=imageFile)
# pdf文档
pdfFile = 'D:/test/test.pdf'
pdfApart = MIMEApplication(open(pdfFile, 'rb').read())
pdfApart.add_header('Content-Disposition', 'attachment', filename=pdfFile)
# excel表
excelFile = 'D:/test/test.xls'
excelApart = MIMEApplication(open(excelFile, 'rb').read())
excelApart.add_header('Content-Disposition', '', filename=excelFile)
#将其附件加入到发送目标
m = MIMEMultipart()
m.attach(textApart)
m.attach(imageApart)
m.attach(excelApart)
#登录
try:
smpt=smtplib.SMTP_SSL(mail_host,port,'utf-8')
smpt.login(send_by,password)
smpt.sendmail(send_by,send_to,m.as_string())
print('success!')
except smtplib.SMTPException as e:
print('Error:',e)
if __name__=="__main__":
title='Test'
content='恭喜你收到邮件!'
send_mail(title,content)
自动转发:
qq邮箱(转发个单个人)需要自行设置,具体如下所示:
进入邮箱->设置->常规->【邮件自动转发】,然后你设置的邮箱会收到一个链接,点击确认即可。