本文實(shí)例為大家分享了python實(shí)現(xiàn)發(fā)送郵件功能的具體代碼,供大家參考,具體內(nèi)容如下
依賴:
Python代碼實(shí)現(xiàn)發(fā)送郵件,使用的模塊是smtplib、MIMEText,實(shí)現(xiàn)代碼之前需要導(dǎo)入包:
import smtplibfrom email.mime.text import MIMEText
使用163郵件發(fā)送郵件,具體代碼實(shí)現(xiàn)如下:
import smtplibfrom email.mime.text import MIMEText'''發(fā)送郵件函數(shù),默認(rèn)使用163smtp:param mail_host: 郵箱服務(wù)器,16郵箱host: smtp.163.com:param port: 端口號(hào),163郵箱的默認(rèn)端口是 25:param username: 郵箱賬號(hào) xx@163.com:param passwd: 郵箱密碼(不是郵箱的登錄密碼,是郵箱的授權(quán)碼):param recv: 郵箱接收人地址,多個(gè)賬號(hào)以逗號(hào)隔開:param title: 郵件標(biāo)題:param content: 郵件內(nèi)容:return:'''def send_mail(username, passwd, recv, title, content, mail_host='smtp.163.com', port=25): msg = MIMEText(content) # 郵件內(nèi)容 msg['Subject'] = title # 郵件主題 msg['From'] = username # 發(fā)送者賬號(hào) msg['To'] = recv # 接收者賬號(hào)列表 smtp = smtplib.SMTP(mail_host, port=port) # 連接郵箱,傳入郵箱地址,和端口號(hào),smtp的端口號(hào)是25 smtp.login(username, passwd) # 登錄發(fā)送者的郵箱賬號(hào),密碼 # 參數(shù)分別是 發(fā)送者,接收者,第三個(gè)是把上面的發(fā)送郵件的 內(nèi)容變成字符串 smtp.sendmail(username, recv, msg.as_string()) smtp.quit() # 發(fā)送完畢后退出smtp print('email send success.')if __name__ == '__main__': email_user = 'xxxx@163.com' # 發(fā)送者賬號(hào) email_pwd = 'xxxxx' # 發(fā)送者密碼,授權(quán)碼 maillist = 'xxxx@qq.com' title = '測試郵件標(biāo)題' content = '這里是郵件內(nèi)容' send_mail(email_user, email_pwd, maillist, title, content)163郵箱的授權(quán)碼獲取方法如下:
1. 登錄163郵箱,點(diǎn)擊設(shè)置-POP3/SMTP/IMAP,如下:

2. 開啟SMTP服務(wù)且可以查詢SMTP的host地址:

3. 點(diǎn)擊客戶端授權(quán)密碼,可以重置授權(quán)碼:

使用QQ郵件發(fā)送郵件,具體代碼實(shí)現(xiàn)如下:
import smtplibfrom email.mime.text import MIMEText'''發(fā)送郵件函數(shù),默認(rèn)使用163smtp:param mail_host: 郵箱服務(wù)器,qq郵箱host: smtp.qq.com:param port: 端口號(hào),qq郵箱的默認(rèn)端口是: 456:param username: 郵箱賬號(hào) xx@163.com:param passwd: 郵箱密碼(不是郵箱的登錄密碼,是郵箱的授權(quán)碼):param recv: 郵箱接收人地址,多個(gè)賬號(hào)以逗號(hào)隔開:param title: 郵件標(biāo)題:param content: 郵件內(nèi)容:return:'''#qq郵箱發(fā)送郵件def send_mail(username, passwd, recv, title, content, mail_host='smtp.qq.com', port=456): msg = MIMEText(content) # 郵件內(nèi)容 msg['Subject'] = title # 郵件主題 msg['From'] = username # 發(fā)送者賬號(hào) msg['To'] = recv # 接收者賬號(hào)列表 smtp = smtplib.SMTP_SSL(mail_host, port=port) # 連接郵箱,傳入郵箱地址,和端口號(hào),smtp的端口號(hào)是25 smtp.login(username, passwd) # 登錄發(fā)送者的郵箱賬號(hào),密碼 # 參數(shù)分別是 發(fā)送者,接收者,第三個(gè)是把上面的發(fā)送郵件的 內(nèi)容變成字符串 smtp.sendmail(username, recv, msg.as_string()) smtp.quit() # 發(fā)送完畢后退出smtp print('email send success.')if __name__ == '__main__': email_user = 'xxx@qq.com' # 發(fā)送者賬號(hào) email_pwd = 'WOSHINIGE123' # 發(fā)送者密碼,授權(quán)碼 maillist = 'xxxx@qq.com' title = '測試郵件標(biāo)題' content = '這里是郵件內(nèi)容' send_mail(email_user, email_pwd, maillist, title, content)
新聞熱點(diǎn)
疑難解答
圖片精選