最近跟著駱昊大神學習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('發送完畢')