Python傳送郵件

2021-10-22 22:34:19 字數 2683 閱讀 1244

from email.mime.multipart import mimemultipart

from email.header import header

from email.mime.text import mimetext

from email.utils import parseaddr, formataddr

import smtplib

from datetime import datetime

from worker.db_connection_api import init_config

class sendmail:

def __init__(self,receive_email):

self.email = init_config.email

self.pwd = init_config.email_pwd

self.receive_email = receive_email

def send_content(self,receiver_name="資料遷移者",title="資料遷移匯出",content="",file_path=""):

now = str(datetime.now())[:19]

msg = mimemultipart()

msg['from'] = self.format_address("<%s>" % self.email)

msg['to'] = self.format_address("%s<%s>" % (receiver_name,self.receive_email))

msg['subject'] = header(title, 'utf-8').encode()

zipfile = file_path.split("/")[-1]

zipapart.add_header('content-disposition', 'attachment', filename=zipfile)

# 郵件正文是mimetext:

msg.attach(mimetext(content, 'plain', 'utf-8'))

msg.attach(zipapart)

# 配置服務, 預設埠25

smtp_server = "smtp.exmail.qq.com"

server = smtplib.smtp(smtp_server, 25)

server.ehlo() # 向gamil傳送smtp 'ehlo' 命令

server.starttls()

server.login(self.email, self.pwd)

server.sendmail(self.email, [self.receive_email], msg.as_string())

server.quit()

def send_error(self,receiver_name="資料遷移者",title="資料遷移匯出",content="",cc_email=none):

# now = str(datetime.now())[:19]

# content = "管理員服務掛了!%s" % now

msg = mimemultipart()

msg['from'] = self.format_address("<%s>" % self.email)

msg['to'] = self.format_address("%s<%s>" % (receiver_name, self.receive_email))

to_address = [self.receive_email]

if cc_email !=none:

msg['cc'] = cc_email

to_address = [self.receive_email] + cc_email.split(',')

# msg.add_header('cc', cc_email)

msg['subject'] = header(title, 'utf-8').encode()

# 郵件正文是mimetext:

msg.attach(mimetext(content, 'plain', 'utf-8'))

# 配置服務, 預設埠25

smtp_server = "smtp.exmail.qq.com"

server = smtplib.smtp(smtp_server, 25)

server.ehlo() # 向gamil傳送smtp 'ehlo' 命令

server.starttls()

server.login(self.email, self.pwd)

server.sendmail(self.email, to_address, msg.as_string())

server.quit()

def format_address(self,s):

name, address = parseaddr(s)

return formataddr((header(name, 'utf-8').encode(), address))

# email = sendmail('[email protected]')

# email.send_content(receiver_name="double",title="測試",file_path="./file.txt")

html傳送郵件 Python傳送郵件(三十)

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

python 傳送郵件

coding utf 8 import smtplib from email.mime.text import mimetext from email.header import header 檔案形式的郵件 def email file mail host smtp.qq.com 郵箱伺服器 ma...

python 傳送郵件

smtp mail transfer protocol 即簡單郵件傳輸協議,它是一組用於由源位址到目的位址傳送郵件的規則,由它來控制信件的中轉方式。python的smtplib提供了一種很方便的途徑傳送電子郵件。它對smtp協議進行了簡單的封裝。直接貼 coding utf 8 import smt...