from os import name
import smtplib
import ssl
from os.path import basename
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email import encoders
from email.mime.base import MIMEBase
smtpserver = "smtp.163.com"
port = 465
sender = 'xxxx@163.com'
# psw是你开启smtp之后,163为你提供的一串字符,
psw = 'PHVSSNABXZDIRJUZ'
receiver = ['xxxx@qq.com', 'xxxx@139.com']
subject = '主题:测试邮件'
body = '<p>这个是发送的139的测试邮件</p>'
body = MIMEText(body, "html", 'utf-8')
msg = MIMEMultipart()
msg['from'] = sender
msg['to'] = ','.join(receiver)
msg['subject'] = subject
pdfFile = 'xxxx.pdf'
pdfApart = MIMEApplication(open(pdfFile, 'rb').read())
pdfApart.add_header('Content-Disposition', 'attachment',
filename=('gbk', '', basename(pdfFile)))
encoders.encode_base64(pdfApart)
filename = pdfFile
att = MIMEBase('application', 'octet-stream')
att.set_payload(open(filename, 'rb').read())
att.add_header('Content-Disposition', 'attachment',
filename=('gbk', '', filename))
encoders.encode_base64(att)
imageFile = '银河.jpg'
imageApart = MIMEImage(open(imageFile, 'rb').read(), imageFile.split('.')[-1])
imageApart.add_header('Content-Disposition', 'attachment',
filename=basename(imageFile))
rarFile = 'test.zip'
rarApart = MIMEApplication(open(rarFile, 'rb').read())
rarApart.add_header('Content-Disposition', 'attachment',
filename=basename(rarFile))
msg.attach(body)
msg.attach(att)
msg.attach(pdfApart)
msg.attach(imageApart)
msg.attach(rarApart)
context = ssl.create_default_context()
# ssl加密发送方式
with smtplib.SMTP_SSL(smtpserver, port, context=context) as server:
server.login(sender, psw)
server.sendmail(sender, receiver, msg.as_string())
print("Success")
# 未加密方式 一
with smtplib.SMTP(smtpserver) as server:
server.login(sender,psw)
server.sendmail(sender,receiver,msg.as_string())
print("Success")
# 未加密方式 二
def send():
smtp = smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(sender, psw)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()
【python】邮件相关操作
最新推荐文章于 2024-03-23 07:19:15 发布
该博客演示了如何使用Python的smtplib和email库通过SMTP SSL加密方式发送包含PDF、图片和压缩文件等附件的电子邮件。示例中详细展示了设置邮件头部信息、创建不同类型的MIME对象以及附件编码的过程。
摘要由CSDN通过智能技术生成