python3 新式郵件寫法 附件亂碼 解決

2021-08-31 16:18:42 字數 2050 閱讀 5862

import sys

import re

import mimetypes

import base64

import traceback

from pathlib import purepath

from datetime import date

from calendar import monthrange

import smtplib

from email.headerregistry import address, group

from email.utils import localtime, make_msgid

from email.message import emailmessage

郵件伺服器 = "smtp.exmail.qq.com"

郵件伺服器_埠 = 465

傳送者賬號 = "[email protected]"

傳送者密碼 = "admin"

傳送者暱稱 = "公司"

def get_type(path):

ctype, encoding = mimetypes.guess_type(path)

if ctype is none or encoding is not none:

return ctype.split('/', 1)

def dd_b64(headstr):

"""對郵件header及附件的檔名進行兩次base64編碼,防止outlook中亂碼。email庫原始碼中先對郵件進行一次base64解碼然後組裝郵件,所以兩次編碼"""

headstr = '=?utf-8?b?' + base64.b64encode(headstr.encode('utf-8')).decode() + '?='

headstr = '=?utf-8?b?' + base64.b64encode(headstr.encode('utf-8')).decode() + '?='

return headstr

def make_msg(to_name, to_addrs, html_table):

msg = emailmessage()

msg['from'] = address(dd_b64(傳送者暱稱), addr_spec = 傳送者賬號) # 省略addr_spec會出現 由 *** 代發

msg['to'] = address(dd_b64(to_name), addr_spec = to_addrs)

msg['subject'] = 郵件主題

msg['date'] = localtime()

msg_cid = make_msgid()

html_table = html_table.replace('', f'

msg.add_alternative(html_table, subtype = 'html')

# msg.set_content(html_table,subtype = 'html')

path = r"e:\onedrive\\桌布\forests2.jpg"

with open(path, 'rb') as img:

msg.get_payload()[0].add_related(img.read(), *get_type(path), cid = msg_cid)

path = r"c:\users\sharp\desktop\新建 microsoft excel 工作表.xlsx"

with open(path, 'rb') as fi:

msg.add_attachment(fi.read(), *get_type(path), filename = dd_b64(purepath(path).name))

return msg

server = smtplib.smtp_ssl(郵件伺服器, 郵件伺服器_埠)

server.login(傳送者賬號, 傳送者密碼)

server.send_message(msg)

解決亂碼的中心就是先兩次base64,原因在**的注釋中。

python 傳送郵件,附件郵件

1,傳送郵件 import smtplib from email.mime.text import mimetext msg from sunruirui1028 163.com 傳送方郵箱 passwd srui1028 填入傳送方郵箱的授權碼 msg to 1048786140 qq.com 收...

Python3實現郵件群發

1 在 mysql 資料庫建立 mail 資料庫,並建立 mail 表 2 將郵箱的電子郵件位址存在於mail 表中 3 編寫 python 程式 coding utf 8 import smtplib from email.mime.text import mimetext import time...

初識python3郵件傳送

前不久學習了一下python是如何傳送郵件到指定郵箱,python使用版本為python3.7。usr bin python3 匯入smtplib包,引用對應外掛程式 import smtplib from email.mime.text import mimetext from email.uti...