python3使用smtplib發送郵件,帶xlsx附件


一、概述

最近在做一個統計報表,需要發送郵件,並帶附件的。

在之前的文章中

https://www.cnblogs.com/xiao987334176/p/10022026.html

已經實現了發送郵件,但是沒有實現發送附件功能。

 

二、正式代碼

send_mail.py

注意:此文件名不能是email.py

因為email是python自帶的,否則會報錯

ModuleNotFoundError: No module named 'email.utils'; 'email' is not a package

完整內容如下:

#!/usr/bin/env python3
# coding: utf-8


import smtplib  # 加載smtplib模塊
from email.mime.text import MIMEText
from email.utils import formataddr
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

class SendMail(object):
    def __init__(self,sender,title,content):
        self.sender = sender  #發送地址
        self.title = title  # 標題
        self.content = content  # 發送內容
        self.sys_sender = '123456@163.com'  # 系統賬戶
        self.sys_pwd = '123456'  # 系統賬戶密碼

    def send(self,file_list):
        """
        發送郵件
        :param file_list: 附件文件列表
        :return: bool
        """
        try:
            # 創建一個帶附件的實例
            msg = MIMEMultipart()
            # 發件人格式
            msg['From'] = formataddr(["技術服務部", self.sys_sender])
            # 收件人格式
            msg['To'] = formataddr(["", self.sender])
            # 郵件主題
            msg['Subject'] = self.title

            # 郵件正文內容
            msg.attach(MIMEText(self.content, 'plain', 'utf-8'))

            # 多個附件
            for file_name in file_list:
                print("file_name",file_name)
                # 構造附件
                xlsxpart = MIMEApplication(open(file_name, 'rb').read())
                # filename表示郵件中顯示的附件名
                xlsxpart.add_header('Content-Disposition','attachment',filename = '%s'%file_name)
                msg.attach(xlsxpart)

            # SMTP服務器
            server = smtplib.SMTP_SSL("smtp.163.com", 465,timeout=10)
            # 登錄賬戶
            server.login(self.sys_sender, self.sys_pwd)
            # 發送郵件
            server.sendmail(self.sys_sender, [self.sender, ], msg.as_string())
            # 退出賬戶
            server.quit()
            return True
        except Exception as e:
            print(e)
            return False

if __name__ == '__main__':
    # 發送地址
    sender = "88888888@qq.com"
    # 標題
    title = "統計"
    # 發送內容
    content = "2019-11-01 ~ 2019-11-30 統計,見附件!"
    # 附件列表
    file_list = ["工作.xls","外出.xls"]
    ret = SendMail(sender, title, content).send(file_list)
    print(ret,type(ret))

 

注意:附件是和python文件在同一目錄,請根據實際情況,修改附件的路徑。

阿里雲服務器,從即日起,不再提供25端口郵件服務 。必須使用SSL加密465端口發信!

所以上面的代碼中,改成了SMTP_SSL,並使用了465端口。

 

執行腳本,查看郵件,效果如下:

本文參考鏈接:

https://blog.csdn.net/sempronx86/article/details/83753689

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM