python如何實現電子郵件的傳送
阿新 • • 發佈:2019-01-05
註明:郵箱如果傳送失敗,則會報錯,可以使用異常處理來檢測郵件是否會發送失敗
常用SMTP地址
1、QQ郵箱(mail.qq.com)
POP3伺服器地址:pop.qq.com(埠:110)
SMTP伺服器地址:smtp.qq.com(埠:25)
2、搜狐郵箱(sohu.com):
POP3伺服器地址:pop3.sohu.com(埠:110)
SMTP伺服器地址:smtp.sohu.com(埠:25)
3、HotMail郵箱(hotmail.com):
POP3伺服器地址:pop.live.com(埠:995)
SMTP伺服器地址:smtp.live.com(埠:587)
4、移動139郵箱:
POP3伺服器地址:POP.139.com(埠:110)
SMTP伺服器地址:SMTP.139.com(埠:25)
5、景安網路郵箱:
POP3伺服器地址:POP.zzidc.com(埠:110)
SMTP伺服器地址:SMTP.zzidc.com(埠:25)
電子郵件
python傳送電子郵件時,使用標準庫中的smtplib和email,smptlib中有一個SMTP類,需要傳送郵件時,初始化該類返回smtpserver物件,使用login登陸MUA,使用sendmail方法傳送郵件,郵件的正文用email.mime.text.MIMEText物件進行描述
簡單電子郵件傳送程式
from email.mime.text import MIMEText msg = MIMEText('hello message','plain', 'utf-8') from_addr = '
[email protected]' to_addr = '[email protected]' sub_msg = 'hello' smtp_server = 'smtp.163.com' import smtplib # 初始化smtp物件,傳入伺服器地址與埠號 server = smtplib.SMTP(smtp_server,25) # 設定除錯模式可以讓我們看到傳送郵件過程中的資訊 server.set_debuglevel(1) # 登陸MUA,使用賬戶與授權碼登陸 server.login(from_addr, 'yourpassword') msg['From'] = from_addr msg['To'] = to_addr msg['Subject'] = 'important message' server.sendmail(from_addr, [to_addr], msg.as_string())
郵件被放入垃圾郵件中,如下
傳送帶附件的電子郵件
from email.mime.text import MIMEText
from smtplib import SMTP
from email.mime.multipart import MIMEMultipart
from_addr = '[email protected]'
to_addr = '[email protected]'
smtp_server = 'smtp.163.com'
smtp_port = 25
subject_msg = 'subject'
mul_msg = MIMEMultipart()
mul_msg['From'] = from_addr
mul_msg['To'] = to_addr
mul_msg['Subject'] = subject_msg
msg = MIMEText('\n\rimportant message\n\r', 'plain', 'utf-8')
mul_msg.attach(msg)
att1 = MIMEText(open('program.txt','rb').read(), 'base64', 'utf-8')
att1['Content-Type'] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment;filename="program.txt"'
mul_msg.attach(att1)
smtp = SMTP(smtp_server, smtp_port)
smtp.login(from_addr, 'youpass')
smtp.set_debuglevel(1)
smtp.sendmail(from_addr, to_addr, mul_msg.as_string())
smtp.close()
使用第三方開源庫yagmail傳送電子郵件
import yagmail
yag = yagmail.SMTP(user='[email protected]', password='you pass', host='smtp.qq.com', port=25)
contents = ['import message','program.txt']
yag.send(to='dest', subject='subject', contents=contents)
使用pop3協議用網易郵箱傳送郵件時,容易被網易識別為垃圾郵件,可以使用qq郵箱