python smtp发送邮件 附件 中文名乱码 问题

重点

   mime.add_header('Content-Disposition', 'attachment', filename=( make_header([(file_name, 'UTF-8')]).encode('UTF-8')))

完整代码可以发送多个附件

import smtplib
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.header import Header, make_header
from email.utils import COMMASPACE, formatdate
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
from email import encoders
from datetime import datetime
from config import mail_tail

import time, os




SMTP_IP = 'sftp.gmail.com'

SMTP_PORT = 25  # 587

EMAIL_FROM = 'rpa05@rpa.com'
EMAIL_PASSWORD = '82767630'

SMTP_CONTENT_TYPE_HTML = 'html'
SMTP_CONTENT_TYPE_TEXT = 'text'


# 第三方 SMTP 服务
mail_host = SMTP_IP  # 设置服务器
mail_user = EMAIL_FROM # 用户名
mail_pass = EMAIL_PASSWORD  # 口令

sender = EMAIL_FROM


to = cc = receivers = ['yu@rpa.com']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

week = time.strftime("%W")
year = time.strftime("%Y")
day = datetime.now().strftime('%Y%m%d')

mail_msg = mail_tail




def send_mail(mail_msg, subject, to, cc, bcc, file_name=None, file_path=None, name=None):
    message = MIMEMultipart('related')
    # message = MIMEText(mail_msg, 'html', 'utf-8')
    message['From'] = 'rpa05@rpa.com'

    message['To'] = COMMASPACE.join(to)
    message['Cc'] = COMMASPACE.join(cc)
    msgAlternative = MIMEMultipart('alternative')
    message.attach(msgAlternative)

    #添加附件

    # att1 = MIMEBase(open(file_path, 'rb').read(), 'base64')
    # att1["Content-Type"] = 'application/octet-stream'
    # # 这里的filename可以任意写,写什么名字,邮件中显示什么名字
    # att1["Content-Disposition"] = f'attachment; filename={file_name}'
    # message.attach(att1)

    if file_path:
        print('os path', os.path.exists(file_path))
        a = os.path.exists(file_path)
        while not a:
            print('while os path', os.path.exists(file_path))
            time.sleep(0.5)
            a = os.path.exists(file_path)


    if file_path:
        with open(file_path, 'rb') as f:
            # 设置附件的MIME和文件名,这里是png类型:
            mime = MIMEBase('application','vnd.ms-excel') #, filename=file_name
            # 加上必要的头信息:
            mime.add_header('Content-Disposition', 'attachment', filename=file_name)
            mime.add_header('Content-ID', '<0>')
            mime.add_header('X-Attachment-Id', '0')
            # 把附件的内容读进来:
            mime.set_payload(f.read())
            # 用Base64编码:
            encoders.encode_base64(mime)
            # 添加到MIMEMultipart:
            message.attach(mime)


    subject = subject
    message['Subject'] = Header(subject)
    message['Date'] = formatdate(localtime=True)
    msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8'))

    # 指定图片为当前目录
    # fp = open(img, 'rb')
    # msgImage = MIMEImage(fp.read())
    # fp.close()

    # 定义图片 ID,在 HTML 文本中引用
    # msgImage.add_header('Content-ID', '<image1>')
    # message.attach(msgImage)

    server = smtplib.SMTP('10.10.10.10:25')

    server.ehlo_or_helo_if_needed()
    server.ehlo()  # 向Gamil发送SMTP 'ehlo' 命令
    server.starttls()
    # server.login(sender, mail_pass)
    print(datetime.now())
    print("邮件发送成功---------->",name)
    if file_path:
        os.remove(file_path)

 
    server.sendmail('rpa@rpa.com', to + cc + bcc , message.as_string())
    server.quit()


def send_mail_multi_attch(mail_msg, subject, to, cc, bcc, file_list=None,  name=None):
    message = MIMEMultipart('related')
    # message = MIMEText(mail_msg, 'html', 'utf-8')
    message['From'] = 'rpa05@rpa.com'
  
    message['To'] = COMMASPACE.join(to)
    message['Cc'] = COMMASPACE.join(cc)
    msgAlternative = MIMEMultipart('alternative')
    message.attach(msgAlternative)

    #添加附件

    # att1 = MIMEBase(open(file_path, 'rb').read(), 'base64')
    # att1["Content-Type"] = 'application/octet-stream'
    # # 这里的filename可以任意写,写什么名字,邮件中显示什么名字
    # att1["Content-Disposition"] = f'attachment; filename={file_name}'
    # message.attach(att1)




    if file_list:
        for index, file in enumerate(file_list):
            file_path = file.get('path')
            file_name = file.get('name')
            with open(file_path, 'rb') as f:
                    # 设置附件的MIME和文件名,这里是png类型:
                    # mime = MIMEBase('application','vnd.ms-excel') #, filename=file_name
                    mime = MIMEBase('application','octet-stream') #, filename=file_name
                    # 加上必要的头信息:
                    print('file_name', file_name)
                    mime.add_header('Content-Disposition', 'attachment', filename=( make_header([(file_name, 'UTF-8')]).encode('UTF-8')))
                    mime.add_header('Content-ID', f'<{index}>')
                    mime.add_header('X-Attachment-Id', f'{index}')
                    # 把附件的内容读进来:
                    mime.set_payload(f.read())
                    # 用Base64编码:
                    encoders.encode_base64(mime)
                    # 添加到MIMEMultipart:
                    message.attach(mime)



    subject = subject
    message['Subject'] = Header(subject)
    message['Date'] = formatdate(localtime=True)
    msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8'))

    # 指定图片为当前目录
    # fp = open(img, 'rb')
    # msgImage = MIMEImage(fp.read())
    # fp.close()

    # 定义图片 ID,在 HTML 文本中引用
    # msgImage.add_header('Content-ID', '<image1>')
    # message.attach(msgImage)

    server = smtplib.SMTP('10.10.10.10:25')

    server.ehlo_or_helo_if_needed()
    server.ehlo()  # 向Gamil发送SMTP 'ehlo' 命令
    server.starttls()
    # server.login(sender, mail_pass)
    print(datetime.now())
    print("邮件发送成功---------->",name)
    # if file_path:
    #     os.remove(file_path)

   
    server.sendmail('rpa@rpa.com', to + cc + bcc , message.as_string())
    server.quit()

if __name__ == '__main__':
    pass

参考
https://blog.csdn.net/u013948083/article/details/95313594
https://segmentfault.com/q/1010000016296204/

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值