发布时间:2019-09-26 07:32:38编辑:auto阅读(1804)
SMTP是Internet邮件传输的标准(wiki)。Python提供了内置的对SMTP支持的模块,其中,email负责构造邮件,smtplib负责邮件发送。
以下代码实现了简单的纯文本邮件发送,可以发送多人,抄送多人。
import smtplib
from email.mime.text import MIMEText
from email.header import Header
global smtplibobj
def init(host,port,user,password):
global smtplibobj
smtplibobj = smtplib.SMTP_SSL(host=host,port=port)
smtplibobj.set_debuglevel(1)
smtplibobj.ehlo()
smtplibobj.login(user=user,password=password)
def quit():
global smtplibobj
smtplibobj.quit()
def sendmail(host,port,user,password,from_addr,to_addr,cc_addr,msg):
global smtplibobj
init(host=host,port=port,user=user,password=password)
try:
smtplibobj.sendmail(from_addr=from_addr, to_addrs=to_addr.split(",") + cc_addr.split(","), msg=msg)
print("邮件发送成功!")
except smtplib.SMTPException:
print("Error:邮件发送失败!")
quit()
def setcontext(from_addr,to_addr,cc_addr,subject,context):
msg = MIMEText(context, "plain", "utf-8")
msg['From'] = Header(from_addr, "utf-8")
msg['To'] = Header(to_addr, "utf-8")
msg['Subject'] = Header(subject, "utf-8")
msg['Cc'] = Header(cc_addr,"utf-8")
# print(msg)
return msg.as_string()
if __name__ == '__main__':
host = "xx.xx.xx"
port = xx
user = "xxx"
password = "xxx"
from_addr = "xxx"
to_addr = "xxx"
cc_addr = "xxx"
msg = setcontext(from_addr=from_addr,to_addr=to_addr,cc_addr=cc_addr,subject="Test",context="忽略此邮件...")
sendmail(host=host,port=port,user=user,password=password,from_addr=from_addr,to_addr=to_addr,cc_addr=cc_addr,msg=msg)
smtplibobj.set_debuglevel(1)
设置后可以打印出和SMTP服务器之间交互的所有信息。smtplib.SMTP_SSL(host=host,port=port)
(即上文代码中的方式)创建对象;若使用tls,则用smtplib.SMTP(host=host,port=port)
的方式创建对象,并在smtplibobj.ehlo()
后增加smtplibobj.starttls()
开启加密传输。是否支持tls,可以从eclo的返回值来确认。如下图:
上一篇: python3微信企业号 发送图文
下一篇: python3实现多线程ping一个网段
47754
46259
37140
34647
29238
25896
24766
19870
19433
17924
5724°
6329°
5845°
5897°
6998°
5835°
5854°
6368°
6323°
7688°