我們在開發程序的時候,有時候需要開發一些自動化的任務,執行完之后,將結果自動的發送一份郵件,python發送郵件使用smtplib模塊,是一個標準包,直接import導入使用即可,代碼如下:
import smtplib from email.mime.text import MIMEText email_host = 'smtp.163.com' #郵箱地址 email_user = 'xxxx@163.com' # 發送者賬號 email_pwd = 'xxxx' # 發送者密碼 maillist ='511402865@qq.com' #收件人郵箱,多個賬號的話,用逗號隔開 me = email_user msg = MIMEText('郵件發送測試內容') # 郵件內容 msg['Subject'] = '郵件測試主題' # 郵件主題 msg['From'] = me # 發送者賬號 msg['To'] = maillist # 接收者賬號列表 smtp = smtplib.SMTP(email_host,port=25) # 連接郵箱,傳入郵箱地址,和端口號,smtp的端口號是25 smtp.login(email_user, email_pwd) # 發送者的郵箱賬號,密碼 smtp.sendmail(me, maillist, msg.as_string()) # 參數分別是發送者,接收者,第三個是把上面的發送郵件的內容變成字符串 smtp.quit() # 發送完畢后退出smtp print ('email send success.')
下面是發送帶附件的郵件
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='發送郵件測試' 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))#郵件正文的內容 msg['Subject'] = title # 郵件主題 msg['From'] = username # 發送者賬號 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()
當然,我們可以封裝成一個函數,使用的時候,直接調用函數,傳入郵箱賬號密碼,收件人,發件人,標題和內容即可。
import smtplib from email.mime.text import MIMEText def send_mail(username,passwd,recv,title,content,mail_host='smtp.163.com',port=25): ''' 發送郵件函數,默認使用163smtp :param username: 郵箱賬號 xx@163.com :param passwd: 郵箱密碼 :param recv: 郵箱接收人地址,多個賬號以逗號隔開 :param title: 郵件標題 :param content: 郵件內容 :param mail_host: 郵箱服務器 :param port: 端口號 :return: ''' msg = MIMEText(content) # 郵件內容 msg['Subject'] = title # 郵件主題 msg['From'] = username # 發送者賬號 msg['To'] = recv # 接收者賬號列表 smtp = smtplib.SMTP(mail_host,port=port) # 連接郵箱,傳入郵箱地址,和端口號,smtp的端口號是25 smtp.login(username, passwd) # 發送者的郵箱賬號,密碼 smtp.sendmail(username, recv, msg.as_string()) # 參數分別是發送者,接收者,第三個是把上面的發送郵件的內容變成字符串 smtp.quit() # 發送完畢后退出smtp print ('email send success.') email_user = 'xxxx@163.com' # 發送者賬號 email_pwd = 'xxxxx' # 發送者密碼 maillist ='511402865@qq.com' title = '測試郵件標題' content = '這里是郵件內容' send_mail(email_user,email_pwd,maillist,title,content)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
