python3利用smtplib發送、抄送郵件並附帶附件


python3利用smtplib發送、抄送郵件並附帶附件

1. 導包

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import logging

2. 定義發送郵件函數

def send_mail(MAIL_SERVER, MAIL_USERNAME, MAIL_PASSWORD, accept_list, Cc_list, SUBJECT, text, file_name):
	
	message = MIMEMultipart()
	message['From'] = MAIL_USERNAME  # 發件人
	message['To'] = ";".join(accept_list)  # 收件人,將列表轉換為字符串
	message["Cc"] = ";".join(Cc_list)  # 抄送人,將列表轉換為字符串
	message['Subject'] = SUBJECT  # 郵件主題
	message.attach(MIMEText(text, 'plain', 'utf-8'))  # 格式化郵件內容,編碼為utf-8

	att1 = MIMEText(open(file_name, 'rb').read(), 'base64', 'utf-8')  # 添加附件
	att1["Content-Type"] = 'application/octet-stream'  # 設置類型
	att1["Content-Disposition"] = 'attachment; filename="{0}"'.format("test.xlsx")  # 設置郵件用現實的名稱
	message.attach(att1)

	try:
		mailServer = smtplib.SMTP(MAIL_SERVER, 25)  # 25為端口號(郵件)
		# 登錄郵箱
		mailServer.login(MAIL_USERNAME, MAIL_PASSWORD)  # 需要的是,郵箱的地址和授權密碼
		# 發送文件
		mailServer.sendmail(MAIL_USERNAME, accept_list + Cc_list, message.as_string())
		mailServer.close()    # 關閉連接
		return True
	except Exception as e:
		# logging.debug(e)
		print(e)
		return False

3. 調用發送郵件函數

def main():

	MAIL_SERVER = 'smtp.qq.com'  # smtp服務器
	MAIL_USERNAME = '*****@qq.com'  # 發件人
	MAIL_PASSWORD = '**********'  # 發送者授權碼
	accept_list = ['****@163.com', '*****@qq.com']  # 收件人
	Cc_list = ['*****@qq.com', '*****@qq.com']  # 抄送人
	SUBJECT = "send mail test"  # 主題
	text = "test page"  # 內容
	file_name = "a.xlsx"  # 上傳附件名稱(當前路徑)

	if send_mail(MAIL_SERVER, MAIL_USERNAME, MAIL_PASSWORD, accept_list, Cc_list, SUBJECT, text, file_name):
		logging.debug("Send mail succed!")

	else:
		logging.debug("Send mail failed")


if __name__ == '__main__':
	main()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM