Python 傳送郵件

2021-08-28 02:19:40 字數 2194 閱讀 6304

傳送附件, excel 檔案

注意使用 python 3的環境不會考慮太多 編碼轉化等問題

import smtplib

from email.mime.text import mimetext

from email.mime.multipart import mimemultipart

from email.header import header

from email import encoders

from email.mime.base import mimebase

from email.utils import parseaddr, formataddr

from tools.oyyo_datetime import oyyodatetime

smtp_server = '***.com.cn' # 傳送郵件伺服器

from_mail = '***.com.cn' # 傳送郵件使用者名稱

mail_pass = '***' # 密碼

to_mail = ['[email protected]'] # yang

body = " 請查收!"

subject = '請查收!'

class sendemail(object):

def __init__(self):

pass

def formataddr(self, s):

"""格式化郵件位址"""

name, addr = parseaddr(s)

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

def send_email(self, path):

smtp_server = smtp_server

from_mail = from_mail

mail_pass = mail_pass

to_mail = to_mail

body = body

# 構造乙個mimemultipart物件代表郵件本身

msg = mimemultipart()

# header對中文進行轉碼

msg['from'] = header("服務端", 'utf-8')

msg['to'] = header("運營", 'utf-8')

now = oyyodatetime.get_now_string()

sub = subject + " " + now

print(sub)

subject = sub

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

# plain代表純文字

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

# att1 = mimetext(open('aaa.xlsx', 'rb').read(), 'base64', 'utf-8')

att1 = mimetext(open(path, 'rb').read(), 'base64', 'utf-8')

# 這裡的filename可以任意寫,寫什麼名字,郵件中顯示什麼名字

att1["content-disposition"] = 'attachment; filename="useraddress.xlsx"' # 這個名字是和傳送出去保持一致的

msg.attach(att1)

try:

s = smtplib.smtp()

s.connect(smtp_server, "25")

s.login(from_mail, mail_pass)

s.sendmail(from_mail, to_mail, msg.as_string()) # as_string()把mimetext物件變成str

s.quit()

print("成功了")

except smtplib.smtpexception as e:

print(("error: %s") % e)

print("失敗了")

if __name__ == '__main__':

s = sendemail()

# sendmail('請查收!', 'a.txt')

s.send_email("aaa.xlsx")

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...