python之發送郵件

import smtplib
from email.mime.text import MIMEText

mailserver = "smtp.126.com"  #郵箱服務器地址
username_send = '[email protected]'  #郵箱用戶名
password = '*'   #郵箱密碼:需要使用授權碼
username_recv = '[email protected]'  #收件人,多個收件人用逗號隔開
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')

來源:https://www.cnblogs.com/mpp0905/p/8419869.html

 

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

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

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

qq郵箱獲取授權碼的方式

 

 

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

import smtplib
from email.mime.text import MIMEText

mailserver = "smtp.163.com"  #郵箱服務器地址
username_send = '[email protected]'  #郵箱用戶名
password = 'XXXX'   #郵箱密碼:需要使用授權碼
username_recv = '[email protected]'  #收件人,多個收件人用逗號隔開
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 = '[email protected]'  #郵箱用戶名
password = 'las0312e'   #郵箱密碼:需要使用授權碼
username_recv = '[email protected]'  #收件人,多個收件人用逗號隔開
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 ['[email protected]','[email protected]]
        :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 ['[email protected]','[email protected]]
        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='[email protected]',
        passwd='xxxxxx',
        recv=['[email protected]','[email protected]'],
        title='發送郵件20180205',
        content='測試發送郵件,qq發件,接收方一個是163郵箱,另一個是qq郵箱。20180205',
        file=r'E:\\testpy\\python-mpp\\day7\\作業\\data\\mpp.xls',
        ssl=True,
    )
    m.send_mail()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章