python实现邮件的发送
注意:发件人邮箱需要开启‘POP3/SMTP服务’,登录邮箱到设置账户中开启,开启后会给一个授权码(要记下来)
如下代码:

import smtplib
from email.mime.application import MIMEApplication
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


from_mail = 'xxxxxxxx@qq.com'    #发件人邮箱
to_mails = 'xxxxxxxx@qq.com'     #收件人邮箱,添加多个收件人,中间用','隔开
mail_pass = 'xxxxxxxxxxxxxxxx'    #授权码

#编写邮件内容,本内容用的是'plain',也可以使用'html'格式
msg = MIMEText(
    """尊敬的领导,你好:
        填写内容.


祝生活愉快
XXXXXX
    """, "plain", "utf-8")
content_part = msg

#添加附件(word文档)
wordFile = 'D:\文档/word.docx' #需发文件路径
word = MIMEApplication(open(wordFile, 'rb').read())
word.add_header('Content-Disposition', 'attachment', filename='word') #设置附件信息

#添加附件(pdf文档)
pdfFile = 'D:\文档/pdf.pdf'  #需发文件路径
pdf = MIMEApplication(open(pdfFile, 'rb').read())
pdf.add_header('Content-Disposition', 'attachment', filename='pdf')

#添加图片
imageFile = 'D:\img/img.png'
image = MIMEImage(open(imageFile, 'rb').read(), _subtype='octet-stream')
image.add_header('Content-Disposition', 'attachment', filename='img')

m = MIMEMultipart()
m.attach(content_part)  #添加邮件正文内容
m.attach(word)    #添加附件到邮件信息中
m.attach(pdf)
m.attach(image)
m['Subject'] = '我是标题' #邮件主题
m['From'] = from_mail   #发件人
m['To'] = to_mails    #收件人

try:
    server = smtplib.SMTP('smtp.qq.com')
    # 登陆邮箱(参数1:发件人邮箱,参数2:邮箱授权码)
    server.login(from_mail, mail_pass)
    # 发送邮件(参数1:发件人邮箱,参数2:若干收件人邮箱,参数3:把邮件内容格式改为str)
    server.sendmail(from_mail, to_mails.split(','), m.as_string())
    print('success')
    server.quit()
except smtplib.SMTPException as e:
    print('error:', e)  # 打印错误

效果图片:

python 发送带附件的邮件 通过python发送邮件带文件_文件路径