十年網(wǎng)站開發(fā)經(jīng)驗 + 多家企業(yè)客戶 + 靠譜的建站團隊
量身定制 + 運營維護+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
本篇文章為大家展示了如何在python中使用郵件模塊,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
import smtplib from email.mime.text import MIMEText email_host = 'smtp.163.com' #郵箱地址 email_user = 'xxxx@163.com' # 發(fā)送者賬號 email_pwd = 'xxxx' # 發(fā)送者密碼 maillist ='511402865@qq.com' #收件人郵箱,多個賬號的話,用逗號隔開 me = email_user msg = MIMEText('郵件發(fā)送測試內(nèi)容') # 郵件內(nèi)容 msg['Subject'] = '郵件測試主題' # 郵件主題 msg['From'] = me # 發(fā)送者賬號 msg['To'] = maillist # 接收者賬號列表 smtp = smtplib.SMTP(email_host,port=25) # 連接郵箱,傳入郵箱地址,和端口號,smtp的端口號是25 smtp.login(email_user, email_pwd) # 發(fā)送者的郵箱賬號,密碼 smtp.sendmail(me, maillist, msg.as_string()) # 參數(shù)分別是發(fā)送者,接收者,第三個是把上面的發(fā)送郵件的內(nèi)容變成字符串 smtp.quit() # 發(fā)送完畢后退出smtp print ('email send success.')
下面是發(fā)送帶附件的郵件
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart username='xxx@xx.com' email_host = 'smtp.163.com' passwd='123456' recv=['511402865@qq.com',] title='郵件標題' content='發(fā)送郵件測試' msg = MIMEMultipart() file='a.txt' att = MIMEText(open(file,encoding='utf-8').read()) att["Content-Type"] = 'application/octet-stream' att["Content-Disposition"] = 'attachment; filename="%s"'%file msg.attach(att) msg.attach(MIMEText(content))#郵件正文的內(nèi)容 msg['Subject'] = title # 郵件主題 msg['From'] = username # 發(fā)送者賬號 msg['To'] = recv # 接收者賬號列表 #smtp = smtplib.SMTP_SSL(eail_host,port=456)#qq郵箱 smtp = smtplib.SMTP_SSL(eail_host,port=25)#其他郵箱 smtp.login(username,passwd) smtp.sendmail(username,recv,msg.as_string()) smtp.quit()
當然,我們可以封裝成一個函數(shù),使用的時候,直接調(diào)用函數(shù),傳入郵箱賬號密碼,收件人,發(fā)件人,標題和內(nèi)容即可。
import smtplib from email.mime.text import MIMEText def send_mail(username,passwd,recv,title,content,mail_host='smtp.163.com',port=25): ''' 發(fā)送郵件函數(shù),默認使用163smtp :param username: 郵箱賬號 xx@163.com :param passwd: 郵箱密碼 :param recv: 郵箱接收人地址,多個賬號以逗號隔開 :param title: 郵件標題 :param content: 郵件內(nèi)容 :param mail_host: 郵箱服務器 :param port: 端口號 :return: ''' msg = MIMEText(content) # 郵件內(nèi)容 msg['Subject'] = title # 郵件主題 msg['From'] = username # 發(fā)送者賬號 msg['To'] = recv # 接收者賬號列表 smtp = smtplib.SMTP(mail_host,port=port) # 連接郵箱,傳入郵箱地址,和端口號,smtp的端口號是25 smtp.login(username, passwd) # 發(fā)送者的郵箱賬號,密碼 smtp.sendmail(username, recv, msg.as_string()) # 參數(shù)分別是發(fā)送者,接收者,第三個是把上面的發(fā)送郵件的內(nèi)容變成字符串 smtp.quit() # 發(fā)送完畢后退出smtp print ('email send success.') email_user = 'xxxx@163.com' # 發(fā)送者賬號 email_pwd = 'xxxxx' # 發(fā)送者密碼 maillist ='511402865@qq.com' title = '測試郵件標題' content = '這里是郵件內(nèi)容' send_mail(email_user,email_pwd,maillist,title,content)
上述內(nèi)容就是如何在python中使用郵件模塊,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注創(chuàng)新互聯(lián)成都網(wǎng)站設計公司行業(yè)資訊頻道。
另外有需要云服務器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。