Python 發送SMTP郵件的簡單教程
Python使用SMTP發送郵件的兩個模塊:smtplib模塊、email模塊。
smtplib:負責發送郵件 email:負責構建郵件 二、SMTP端口1)未加密端口,smtplib.SMTP接口,端口:252)使用SSL加密,smtplib.SMTP_SSL接口,端口:4653)使用TLS加密,端口:587
三、四大步驟1、構造郵件內容# 純文本msg = MIMEText(content) # 附件msg = MIMEMultipart()2、連接郵件服務器
s = smtplib.SMTP('smtp.qq.com', 25)3、登陸郵件服務器
s.login(msg_from, passwd)
msg_from:指發送者的郵箱
passwd:指發送者的密碼,這個密碼不是你的QQ登陸密碼,而是你在QQ郵箱設置開啟SMTP之后的一個授權碼
s.sendmail(msg_from, msg_to, msg.as_string())
msg_from:發送方msg_to:收件方msg.as_string():要發送的消息
四、常用場景1、純文本郵件import smtplibfrom email.mime.text import MIMETextfrom email.header import Header # 發送者msg_from = '[email protected]' # 這里的密碼不是QQ郵箱的密碼,而是在設置里開啟SMTP服務器后的授權碼passwd = 'xxxxx' # 接受者msg_to = '[email protected]' # 郵件文本content = ’Python 郵件發送測試...’ # 郵件主題subject = 'test' # 生成一個MIMEText對象(還有一些其它參數)msg = MIMEText(content) # 放入郵件主題msg[’Subject’] = Header(subject, ’utf-8’) # 放入發件人msg[’From’] = msg_from try: # 連接郵件服務器 s = smtplib.SMTP('smtp.qq.com', 25) # 登錄到郵箱 s.login(msg_from, passwd) # 發送郵件:發送方,收件方,要發送的消息 s.sendmail(msg_from, msg_to, msg.as_string()) print(’成功’)except s.SMTPException as e: print(e)finally: s.quit()2、發送html文本
import smtplibfrom email.mime.text import MIMETextfrom email.header import Header # 發送者msg_from = '[email protected]' # 這里的密碼不是QQ郵箱的密碼,而是在設置里開啟SMTP服務器后的授權碼passwd = 'xxxx' # 接受者msg_to = '[email protected]' # 郵件文本content = '''<p>Python 郵件發送測試...</p><p><a rel='external nofollow' >這是一個鏈接</a></p>''' # 郵件主題subject = 'test' # 生成一個MIMEText對象(msg = MIMEText(content, ’html’, ’utf-8’) # 放入郵件主題msg[’Subject’] = Header(subject, ’utf-8’) # 放入發件人msg[’From’] = msg_from try: # 連接郵件服務器 s = smtplib.SMTP('smtp.qq.com', 25) # 登錄到郵箱 s.login(msg_from, passwd) # 發送郵件:發送方,收件方,要發送的消息 s.sendmail(msg_from, msg_to, msg.as_string()) print(’成功’)except s.SMTPException as e: print(e)finally: s.quit()3、發送附件
import smtplibfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom email.header import Header # 發送者msg_from = '[email protected]' # 這里的密碼不是QQ郵箱的密碼,而是在設置里開啟SMTP服務器后的授權碼passwd = 'xxxx' # 接受者msg_to = '[email protected]' # 郵件主題subject = 'test' # 生成一個MIMEMultipart對象(msg = message = MIMEMultipart() # 郵件文本message.attach(MIMEText(’這是菜鳥教程Python 郵件發送測試……’, ’plain’, ’utf-8’)) # 放入郵件主題msg[’Subject’] = Header(subject, ’utf-8’) # 放入發件人msg[’From’] = msg_from # 添加附件att1 = MIMEText(open(’./wordcloud_singer.py’, ’rb’).read(), ’base64’, ’utf-8’)att1['Content-Type'] = ’application/octet-stream’att1['Content-Disposition'] = ’attachment; filename='test.txt'’msg.attach(att1) try: # 連接郵件服務器 s = smtplib.SMTP('smtp.qq.com', 25) # 登錄到郵箱 s.login(msg_from, passwd) # 發送郵件:發送方,收件方,要發送的消息 s.sendmail(msg_from, msg_to, msg.as_string()) print(’成功’)except s.SMTPException as e: print(e)finally: s.quit()
以上就是Python 發送SMTP郵件的簡單教程的詳細內容,更多關于Python 發送郵件的資料請關注好吧啦網其它相關文章!
相關文章: