python发送图⽚⽂本wordpdf格式的邮件
今天分享⼀下发送邮件。
在说今天最重要的部分之前,先说说pickle吧。
我觉得把⼀些隐私的数据放在pickle⽂件中是⼀个很好的⽅法。
⽐如我们今天⽤到的,发件⼈的邮箱,发件⼈的密码,收件⼈的邮箱。
def dumpPickle(data, saveLocation, fileName):
os.chdir(saveLocation) #⽂件存放的路径
with open(fileName, 'wb') as f:
pickle.dump(data, f) #导⼊数据data到⽂件f中
print('save data: %s successful' % fileName)
dumpPickle()函数是将数据导出⽣成⼀个pickle⽂件,存放在指定路径
def loadPickle(loadLocation, fileName):
os.chdir(loadLocation) #⽂件读取的路径
with open(fileName, 'rb') as f:
return pickle.load(f) #读取数据
loadPickle()函数是读取指定路径下的⽂件
下⾯是发送邮件的代码:
import os, pickle
import smtplib
import mimetypes
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from import MIMEText
from email.mime.audio import MIMEAudio
from email.mime.image import MIMEImage
ders import encode_base64
def dumpPickle(data, saveLocation, fileName):
os.chdir(saveLocation) #⽂件存放的路径
with open(fileName, 'wb') as f:
pickle.dump(data, f) #导⼊数据data到⽂件f中
print('save data: %s successful' % fileName)
def loadPickle(loadLocation, fileName):
os.chdir(loadLocation) #⽂件读取的路径
with open(fileName, 'rb') as f:
return pickle.load(f) #读取数据
def sendMail(subject, recipient, text, *attachmentFilePaths):
'''发送邮件函数:参数(邮件主题,邮件内容,邮件附件(可多选))'''
msg = MIMEMultipart()  # 发送附件时需调⽤ MIMEMultipart类,创建 MIMEMultipart,并添加信息头
'''
MIME邮件的基本信息、格式信息、编码⽅式等重要内容都记录在邮件内的各种域中,域的基本格式:{域名}:{内容},域由域名后⾯跟“:”再加上域的信息内容域的⾸⾏左侧不能有空⽩字符,⽐如空格或者制表符,占⽤多⾏的域其后续⾏则必须以空⽩字符开头。域的信息内容中还可以包含属性,属性之间以“;”分隔,属    '''
msg['From'] = sender
msg['To'] = ";".join(recipient)
msg['Subject'] = subject
msg.attach(MIMEText(text))
for attachmentFilePath in attachmentFilePaths:  #判断添加哪些附件
msg.attach(getAttachment(attachmentFilePath))  #如果⼊参给定附件⽂件,使⽤attach 发放添加msg头信息
try:
mailServer = smtplib.SMTP('smtp.qq', 587)  # 连接腾讯邮件的服务器;SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,⽤于由源地址        mailServer.ehlo()  # 使⽤starttls ⽅法必须先 ehlo 判断是否是同⼀个地址。。。
mailServer.starttls()  # 以下SMTP都会加密;Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTP commands that follow will be e        mailServer.ehlo()  # You should then call ehlo() again.
mailServer.login(sender, password)  # 登录邮箱
mailServer.sendmail(sender, recipient, msg.as_string())  # 发送邮件(发件⼈,收件⼈,发送内容)
mailServer.close() # 关闭邮件发送服务
print('Sent email to %s successfully' % recipient)
except Exception as e:
print('sendEmai failed %s' % e)
"""part = MIMEApplication(open('foo.mp3','rb').read())
part.add_header('Content-Disposition', 'attachment', filename="foo.mp3")
msg.attach(part) """
def getAttachment(attachmentFilePath):# 获取附件,参数:⽂件路径
import picklecontentType, encoding = mimetypes.guess_type(attachmentFilePath)  # 根据 guess_type⽅法判断⽂件的类型和编码⽅式
if contentType is None or encoding is not None:  # 如果根据⽂件的名字/后缀识别不出是什么⽂件类型
contentType = 'application/octet-stream'# 使⽤默认类型,usable for a MIME content-type header.
mainType, subType = contentType.split('/', 1)  # 根据contentType 判断主类型与⼦类型
file = open(attachmentFilePath, 'rb')
if mainType == 'text':  # 根据主类型不同,调⽤不同的⽂件读取⽅法
attachment = MIMEBase(mainType, subType)  # A subclass of MIMENonMultipart, the MIMEText class is used to create MIME objects of major type t        attachment.set_ad())  # Set the entire message object’s payload(负载) to payload.
encode_base64(attachment)  # Encodes the payload into base64 form and sets the Content-Transfer-Encoding header to base64.
elif mainType == 'message':
attachment = ssage_from_file(file)  # 使⽤message_from_file⽅法,Return a message object structure tree from an open file object
elif mainType == 'image':  # 图⽚
attachment = ad())  #A subclass of MIMENonMultipart, the MIMEImage class is used to create MIME message objects of major type #elif mainType == 'audio':  # ⾳频
#attachment = ad(), _subType=subType)  #A subclass of MIMENonMultipart, the MIMEAudio class is used to create MIME message
else:
attachment = MIMEBase(mainType, subType)  # The MIMEBase class always adds a Content-Type header (based on _maintype, _subtype, and _par        attachment.set_ad())  # Set the entire message object’s payload(负载) to payload.
encode_base64(attachment)  # Encodes the payload into base64 form and sets the Content-Transfer-Encoding header to base64.
file.close()
"""
Content-disposition 是 MIME 协议的扩展,MIME 协议指⽰ MIME ⽤户代理如何显⽰附加的⽂件。Content-disposition其实可以控制⽤户请求所得的内容存为⼀⽂件直接在浏览器上显⽰或者在访问时弹出⽂件下载对话框。 content-disposition = "Content-Disposition" ":" disposition-type *( ";" disposition-parm ) 。
"""
attachment.add_header('Content-Disposition', 'attachment',  filename=os.path.basename(attachmentFilePath))  #Content-Disposition为属性名 dispositio return attachment
#dumpPickle("发件⼈邮箱?发件⼈邮箱密码?['收件⼈邮箱']", os.path.basename('.'), "")
if __name__ == "__main__":
senderInfo = loadPickle(os.path.basename('.'), "")
sender = senderInfo.split("?")[0] #发件⼈邮箱
password = senderInfo.split("?")[1] #发件⼈邮箱密码
recipient = senderInfo.split("?")[2] #收件⼈邮箱
recipient = [recipient[2:-2]] #将string格式的"['收件⼈邮箱']"转换成['收件⼈邮箱']
sendMail('邮件主题', recipient, '发送格式:.jpg, .pdf, .doc, .txt', 'index.jpg', 'Web Scraping with Python.pdf', '短⽂.doc', '短⽂.txt')
下⾯是验证是否发送成功,以及发送内容数据格式是否有误。
收件页⾯:
在以上页⾯可以看到图⽚(这⾥只⽤了⼀种格式,其他常见格式亦可)是正常显⽰,图⽚ok。 以下是预览页⾯,主要查看⽂件是否有损坏,或者⽂件转换出错等问题。
⽂件名在左上⾓。
预览——pdf
预览——txt
预览——doc
txt & doc内容是今天百度新闻⾥的第⼀篇⽂章,见谅,o(^▽^)o

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。