【python】邮件相关操作

该博客演示了如何使用Python的smtplib和email库通过SMTP SSL加密方式发送包含PDF、图片和压缩文件等附件的电子邮件。示例中详细展示了设置邮件头部信息、创建不同类型的MIME对象以及附件编码的过程。
摘要由CSDN通过智能技术生成

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值