python3 群发邮件(处理了附件中文名乱码问题)

最近跟着骆昊大神学习python,练习了发送邮件功能,处理了windows下附件名中文乱码的问题, 感觉挺有用的,记录于此
大佬地址:
知乎:https://zhuanlan.zhihu.com/p/403195489
github: https://github.com/jackfrued/Python-100-Days

代码

import smtplib
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from urllib.parse import quote
import chardet

# 邮件服务域名
EMAIL_HOST = 'smtp.163.com'
# 邮件服务端口
EMAIL_PORT = 465
# 发件人
EMAIL_USER = '自己的邮箱'
# 163的SMTP授权码
EMAIL_AUTH = '163的SMTP授权码'


def send_mail(*, from_user, to_user, subject='', content='', filenames=[]):
    """ 发送邮件
    :param from_user: 发件人
    :param to_user: 收件人
    :param subject: 邮件主题
    :param content: 邮件正文
    :param filenames: 群发附件的文件路径
    :return:
    """
    # 创建邮件主体对象
    email = MIMEMultipart()
    email['From'] = from_user
    email['To'] = to_user
    email['Subject'] = subject
    message = MIMEText(content, 'plain', 'utf-8')
    # 通过attach() 方法将message内容加入MIMEMultipart()容器内
    email.attach(message)
    for filename in filenames:
        with open(filename, 'rb') as file:
            # 获取到右边第一个‘/’的位置
            pos = filename.rfind('/')
            #获取文件名,三目运算符
            display_filename = filename[pos + 1:] if pos >= 0 else filename
            # 将中文文件名处理成百分号编码
            # display_filename = quote(display_filename)
            #base64是为了将二进制数据处理成文本字符,因为邮件传输协议是基于文本的协议,后面的utf-8是指明传输文件的编码
            attachment = MIMEText(file.read(), 'base64', 'utf-8')
            attachment['content-type'] = 'application/octet-stream'
            # 这样写可以处理附件名中文乱码的问题,因为windows下中文名默认是gbk编码
            attachment.add_header('content-disposition', 'attachment', filename=('gbk', '',  display_filename))
            email.attach(attachment)
    try:
        smtp = smtplib.SMTP_SSL(EMAIL_HOST, EMAIL_PORT)
        smtp.login(EMAIL_USER, EMAIL_AUTH)
        smtp.sendmail(from_user, to_user, email.as_string())
        smtp.quit()
        print('success!')
    except smtplib.SMTPException as e:
        print('failure')
        print('e')


if __name__ == '__main__':
    # 收件人
    addressees = ['[email protected]', '[email protected]', '[email protected]', '[email protected]',
                  '[email protected]', '[email protected]']
    names = ['小明', 'x', 'x', 'x', 'x', 'xx']
    others = ['加油', '真能吃', '好菜啊', '该减肥了', '该锻炼了', '好好学习']
    for i in range(0, len(addressees)):
        content = f'xx在学习python, 用python给{names[i]}发送了一封毫无意义的带附件的邮件, 并说了一句{others[i]}'
        subject = f'发送给{names[i]}的带附件的邮件'
        send_mail(from_user=EMAIL_USER, to_user=addressees[i], subject=subject, content=content,
                  filenames=['C:/abc12附件.txt'])
    print('发送完毕')

你可能感兴趣的:(python)