PYTHON 發郵件(解決MAC OS 中文亂碼)

2021-08-18 13:31:52 字數 2746 閱讀 4629

import smtplib

from email.mime.multipart import mimemultipart

from email.mime.text import mimetext

from email.mime.base import mimebase

from utils import dateutil

import logging

import base64

from email import encoders

import time

username = '******@189.cn'

password = '*********'

sender = username

logger = logging.getlogger(__name__)

logger.setlevel(level=logging.debug)

handler = logging.filehandler("out.txt")

handler.setlevel(logging.debug)

formatter = logging.formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

handler.setformatter(formatter)

logger.addhandler(handler)

def sendwithattach(areceiver, acc, asubject, bodycontent, path, filename):

# 構造mimemultipart物件做為根容器

msg = mimemultipart()

# 構造mimetext物件做為郵件顯示內容並附加到根容器

body = mimetext(bodycontent)

msg.attach(body)

# 構造mimebase物件做為檔案附件內容並附加到根容器

# 讀入檔案內容並格式化,此處檔案為當前目錄下,也可指定目錄 例如:open(r'/tmp/123.txt','rb')

part.set_payload(open(path + filename, 'rb').read())

encoders.encode_base64(part)

## 設定附件頭

c = base64.b64encode(filename.encode('utf-8'))

d = str(c).replace('b\'', '').replace('\'', '')

part.add_header('content-disposition', 'attachment', filename='=?utf-8?b?' + d + '?=')

msg.attach(part)

# 設定根容器屬性

msg['subject'] = asubject

msg['from'] = sender

msg['to'] = areceiver

msg['cc'] = acc

msg['date'] = time.strftime('%a, %d %b %y %h:%m:%s %z')

# 如上得到了格式化後的完整文字msg.as_string()

# 用smtp傳送郵件

smtp = smtplib.smtp()

# 服務,如果是163的郵箱,就填上smtp.163.com

## 下面開始真正的傳送郵件了

try:

smtp.connect('smtp.189.cn')

smtp.login(sender, password)

# smtp.sendmail(sender, mail_to, msg.as_string())

smtp.sendmail(sender, areceiver.split(',') + acc.split(','), msg.as_string())

logger.debug('send mail ok!')

except smtplib.smtprecipientsrefused:

logger.debug('recipient refused')

except smtplib.smtpauthenticationerror:

logger.debug('auth error')

except smtplib.smtpsenderrefused:

logger.debug('sender refused')

except smtplib.smtpexception as e:

logger.debug(e.message)

smtp.quit()

return none

if __name__ == '__main__':

areceiver = '******[email protected],******[email protected]'

acc = '*********@189.cn'

path = 'd:\\'

filename = '測試123.xlsx'

asubject = dateutil.getyesterday()

bodycontent = '如有問題請及時反饋'

sendwithattach(areceiver, acc, asubject, bodycontent, path, filename)

print("send over!")

python 發郵件 python發郵件

python提供smtplib模組,該模組定義了乙個smtp客戶端會話物件,可用於使用smtp或esmtp偵聽器守護程式向任何網際網路機器傳送郵件。這是乙個簡單的語法,用來建立乙個smtp物件,稍後將演示如何用它來傳送電子郵件 import smtplib smtpobj smtplib.smtp ...

Python 實現發郵件

usr bin python coding utf 8 import smtplib from email.mime.text import mimetext from email.header import header 第三方 smtp 服務 mail host smtp.163.com 設定伺...

Python自動發郵件

摘要 本文介紹如何使用python發郵件,主要原理是利用qq郵箱傳送郵件 獲得授權碼後將其寫在下面程式中,然後就可以給自己的郵箱發郵件了 使用qq郵箱傳送郵件 content是傳送的內容,格式為 hostusername你自己的qq郵箱名 tousername 接收方的郵箱賬號 import smt...