python3 發送郵件的心得,天天發報表的寶寶們看過來!

很久都沒有更新博客了,是半年時間作了1個創業項目。失敗後總結寶寶我仍是老老實實打工混吃還債吧。 由於長時間作數據運營工做,報表每天見真的很煩。就想一些常規數據軟件本身發算了。因而有了這個研究。html

就用python3作的一個簡單的自動發送腳本。定時發送郵件,還得寫一個數據獲取的心跳,由於是多個數據源。還有一個重要的東西是plt+pillow繪製數據儀表盤導出放到網站上,感受偷懶技術都要上天了!python

本文主要是python發郵件的!測試163,126,qq,阿里郵件推送,均可以用。app

#coding=utf-8
import smtplib
import email

from email.mime.text import MIMEText #html格式郵件
from email.mime.multipart import MIMEMultipart #帶圖片格式郵件
from email.mime.image import MIMEImage #帶圖片格式郵件

# from email.mime.base import MIMEBase
# from email import encoders

# from email.mime.application import MIMEApplication
from email.header import Header


# 發件人地址,經過控制檯建立的發件人地址
username = 'service@nigaea.com'
# 發件人密碼,經過控制檯建立的發件人密碼
password = '*****'
# 自定義的回覆地址
replyto = '765854380@qq.com'
# 收件人地址或是地址列表,支持多個收件人,最多30個
#rcptto = ['***', '***']
rcptto = '******'
# 構建alternative結構
msg = MIMEMultipart('alternative')
msg['Subject'] = Header('自定義信件主題', 'utf-8')
msg['From'] = '%s <%s>' % (Header('自定義發信暱稱','utf-8'), username)
msg['Reply-to'] = replyto
msg['Message-id'] = email.utils.make_msgid()
msg['Date'] = email.utils.formatdate() 


# 構建alternative的text/plain部分
textplain = "hello world!"
textplain = MIMEText('自定義TEXT純文本部分','plain','utf-8')
msg.attach(textplain)
# 構建alternative的text/html部分
# texthtml = MIMEText('自定義HTML超文本部分', _subtype='html', _charset='UTF-8')
# msg.attach(texthtml)

# 帶附件的郵件MIMEApplication
# filename = ['簡歷.pdf','副本.pdf']
# fp = open(filename, 'rb')
# attachfile = MIMEApplication(fp.read())
# fp.close()
# attachfile.add_header('Content-Disposition', 'attachment', filename=filename)
# msg.attach(attachfile)
# 帶多個附件的郵件MIMEApplication
# filename = ['圖片.pdf','副本.pdf']
# for tmp in filename:
#     fp = open(tmp, 'rb')
#     attachfile = MIMEApplication(fp.read())
#     fp.close()
#     attachfile.add_header('Content-Disposition', 'attachment', filename=tmp)
#     msg.attach(attachfile)

#帶附件的郵件MIMEBase
# filename = '圖片.pdf'
# attachfile = MIMEBase('application', 'octet-stream')  
# attachfile.set_payload(open(filename, 'rb').read())  
# attachfile.add_header('Content-Disposition', 'attachment', filename=('utf-8', '', filename) )  
# encoders.encode_base64(attachfile)  
# msg.attach(attachfile)


# 發送郵件
try:
    client = smtplib.SMTP()
    #python 2.7以上版本,若須要使用SSL,能夠這樣建立client
    #client = smtplib.SMTP_SSL()
    #SMTP普通端口爲25或80
    client.connect('smtpdm.aliyun.com', 25)
    #開啓DEBUG模式
    # client.set_debuglevel(0)
    client.login(username, password)
    #發件人和認證地址必須一致
    #備註:若想取到DATA命令返回值,可參考smtplib的sendmaili封裝方法:
    #      使用SMTP.mail/SMTP.rcpt/SMTP.data方法
    client.sendmail(username, rcptto, msg.as_string())
    client.quit()
    print('email send success!')
except smtplib.SMTPConnectError as e:
    print('郵件發送失敗,鏈接失敗:', e.smtp_code, e.smtp_error)
except smtplib.SMTPAuthenticationError as e:
    print('郵件發送失敗,認證錯誤:', e.smtp_code, e.smtp_error)
except smtplib.SMTPSenderRefused as e:
    print('郵件發送失敗,發件人被拒絕:', e.smtp_code, e.smtp_error)
except smtplib.SMTPRecipientsRefused as e:
    print('郵件發送失敗,收件人被拒絕:', e.smtp_code, e.smtp_error)
except smtplib.SMTPDataError as e:
    print('郵件發送失敗,數據接收拒絕:', e.smtp_code, e.smtp_error)
except smtplib.SMTPException as e:
    print('郵件發送失敗, ', e.message)
except Exception as e:
    print('郵件發送異常, ', str(e))

這個是借鑑了阿里雲郵件推送服務的實例,感受幾乎已經很好解決所需的問題。含ssl的解決方式、多個附件的、帶圖片的、html格式的,郵件錯誤類型等。能夠後續自行發揮了。測試

做爲腳本測試的化上面就已經夠了,但是要天天更新數據自行發郵件還須要更多操做。網上搜索了一個很不錯的類的寫法,能夠參考一下:網站

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

class mailsender(object):
	_from = None
	_attachments = []

	def __init__(self, smtpsvr, port):
		self.smtp = smtplib.SMTP()
		print("connecting....")
		self.smtp.connect(smtpsvr, port)
		print("connected!")

	def login(self, user, pwd):
		self._from = user
		print("login ...")
		self.smtp.login(user, pwd)

	def add_attachment(self, filename):
		att = MIMEBase('application', 'octet-stream')
		att.set_payload(open(filename,'rb').read())
		att.add_header('Content-Disposition', 'attachment', filename = ('gbk','',filename))
		encoders.encode_base64(att)
		self._attachments.append(att)

	def send(self, subject, content, to_addr):
		msg = MIMEMultipart('alternative')
		contents = MIMEText(content, 'html', _charset ='utf-8')
		msg['subject'] = subject
		msg['from'] = self._from
		msg['to'] = to_addr
		for att in self._attachments:
			msg.attach(att)
		msg.attach(contents)
		try:
			self.smtp.sendmail(self._from, to_addr, msg.as_string())
			return True
		except Exception as e:
			print(str(e))
			return False
	def close(self):
		self.smtp.quit
		print("logout!")

mail = mailsender('smtp.163.com','25')
mail.login('nigaea@163.com','******')
mail.add_attachment('簡.pdf')
mail.send('hello test','試','buwangyouxil@163.com')
mail.close()

個人博客地址:https://www.nigaea.com/programmer/162.htmlui

相關文章
相關標籤/搜索