python之發送郵件


在學習怎么使用python發送郵件之前,首先要知道什么是授權碼。

授權碼是用於登錄第三方郵件客戶端的專用密碼

網易郵箱獲取授權碼的方式

qq郵箱獲取授權碼的方式

 

 

接下來我們看怎么使用python自動發送郵件

import smtplib
from email.mime.text import MIMEText

mailserver = "smtp.163.com" #郵箱服務器地址
username_send = 'test@163.com' #郵箱用戶名
password = 'XXXX' #郵箱密碼:需要使用授權碼
username_recv = 'test@qq.com' #收件人,多個收件人用逗號隔開
mail = MIMEText('這是發用的郵件內容')
mail['Subject'] = '這是郵件主題'
mail['From'] = username_send #發件人
mail['To'] = username_recv #收件人;[]里的三個是固定寫法,別問為什么,我只是代碼的搬運工
smtp = smtplib.SMTP(mailserver,port=25) # 連接郵箱服務器,smtp的端口號是25
# smtp=smtplib.SMTP_SSL('smtp.qq.com',port=465) #QQ郵箱的服務器和端口號
smtp.login(username_send,password) #登錄郵箱
smtp.sendmail(username_send,username_recv,mail.as_string())# 參數分別是發送者,接收者,第三個是把上面的發送郵件的內容變成字符串
smtp.quit() # 發送完畢后退出smtp
print ('success')

發送后的郵件

升級一下郵件內容,我們發送一封帶有附件的郵件

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

mailserver = "smtp.163.com" #郵箱服務器地址
username_send = 'mapeipei04265@163.com' #郵箱用戶名
password = 'las0312e' #郵箱密碼:需要使用授權碼
username_recv = '272932709@qq.com' #收件人,多個收件人用逗號隔開
mail = MIMEMultipart()
# file = r'E:\\testpy\\python-mpp\\day8\\練習\\sendmail.py'
# att = MIMEText(open(file,encoding='utf-8').read()) #這個只可以發送py或者txt附件,復雜一點的就會報錯
file=r'E:\\testpy\\python-mpp\\day7\\作業\\data\\mpp.xls'
att = MIMEText(open(file, 'rb').read(),"base64", "utf-8") #這個可以發送復雜的附件,比如附件為表格
att["Content-Type"] = 'application/octet-stream'

#這行是把附件的格式進行一些處理,不知道為啥要這么寫,但是如果不寫接收到的附件已經不是表格樣式了
new_file='=?utf-8?b?' + base64.b64encode(file.encode()).decode() + '?='

att["Content-Disposition"] = 'attachment; filename="%s"'%new_file
mail.attach(att)
mail.attach(MIMEText('這是一封帶有附件的郵件正文內容,假裝很長'))#郵件正文的內容
mail['Subject'] = '這是郵件主題'
mail['From'] = username_send #發件人
mail['To'] = username_recv #收件人;[]里的三個是固定寫法,別問為什么,我只是代碼的搬運工
smtp = smtplib.SMTP(mailserver,port=25) # 連接郵箱服務器,smtp的端口號是25
# smtp=smtplib.SMTP_SSL('smtp.qq.com',port=465) #QQ郵箱的服務器和端口號
smtp.login(username_send,password) #登錄郵箱
smtp.sendmail(username_send,username_recv,mail.as_string())# 參數分別是發送者,接收者,第三個是把上面的發送郵件的內容變成字符串
smtp.quit() # 發送完畢后退出smtp
print ('success')

發送后的郵件

 

 最后放上一個老師封裝好的發送郵件的函數,使用的時候直接調用即可

import smtplib,os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import base64
class SendMail(object):
def __init__(self,username,passwd,recv,title,content,
file=None,ssl=False,
email_host='smtp.qq.com',port=25,ssl_port=465):
'''
:param username: 用戶名
:param passwd: 密碼
:param recv: 收件人,多個要傳list ['a@qq.com','b@qq.com]
:param title: 郵件標題
:param content: 郵件正文
:param file: 附件路徑,如果不在當前目錄下,要寫絕對路徑,默認沒有附件
:param ssl: 是否安全鏈接,默認為普通
:param email_host: smtp服務器地址,默認為163服務器
:param port: 非安全鏈接端口,默認為25
:param ssl_port: 安全鏈接端口,默認為465
'''
self.username = username #用戶名
self.passwd = passwd #密碼
self.recv = recv #收件人,多個要傳list ['a@qq.com','b@qq.com]
self.title = title #郵件標題
self.content = content #郵件正文
self.file = file #附件路徑,如果不在當前目錄下,要寫絕對路徑
self.email_host = email_host #smtp服務器地址
self.port = port #普通端口
self.ssl = ssl #是否安全鏈接
self.ssl_port = ssl_port #安全鏈接端口
def send_mail(self):
msg = MIMEMultipart()
#發送內容的對象
if self.file:#處理附件的
file_name = os.path.split(self.file)[-1]#只取文件名,不取路徑
try:
f = open(self.file, 'rb').read()
except Exception as e:
raise Exception('附件打不開!!!!')
else:
att = MIMEText(f,"base64", "utf-8")
att["Content-Type"] = 'application/octet-stream'
#base64.b64encode(file_name.encode()).decode()
new_file_name='=?utf-8?b?' + base64.b64encode(file_name.encode()).decode() + '?='
#這里是處理文件名為中文名的,必須這么寫
att["Content-Disposition"] = 'attachment; filename="%s"'%(new_file_name)
msg.attach(att)
msg.attach(MIMEText(self.content))#郵件正文的內容
msg['Subject'] = self.title # 郵件主題
msg['From'] = self.username # 發送者賬號
msg['To'] = ','.join(self.recv) # 接收者賬號列表
if self.ssl:
self.smtp = smtplib.SMTP_SSL(self.email_host,port=self.ssl_port)
else:
self.smtp = smtplib.SMTP(self.email_host,port=self.port)
#發送郵件服務器的對象
self.smtp.login(self.username,self.passwd)
try:
self.smtp.sendmail(self.username,self.recv,msg.as_string())
pass
except Exception as e:
print('出錯了。。',e)
else:
print('發送成功!')
self.smtp.quit()


if __name__ == '__main__':
m = SendMail(
username='test@qq.com',
passwd='xxxxxx',
recv=['test001@163.com','test002@qq.com'],
title='發送郵件20180205',
content='測試發送郵件,qq發件,接收方一個是163郵箱,另一個是qq郵箱。20180205',
file=r'E:\\testpy\\python-mpp\\day7\\作業\\data\\mpp.xls',
ssl=True,
)
m.send_mail()



 


免責聲明!

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



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