Python学习笔记-邮件模块SMTP

来源:互联网 发布:深入理解大数据 pdf 编辑:程序博客网 时间:2024/06/18 12:37

smtplib模块:

SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。

python的smtplib提供了一种很方便的途径发送电子邮件。它对smtp协议进行了简单的封装。

Python创建 SMTP 对象语法如下:

1
2
import smtplib
smtpObj = smtplib.SMTP( [host [port [local_hostname]]] )  

参数说明:

  • host: SMTP 服务器主机。 你可以指定主机的ip地址或者域名如: runoob.com,这个是可选参数。
  • port: 如果你提供了 host 参数, 你需要指定 SMTP 服务使用的端口号,一般情况下 SMTP 端口号为25。
  • local_hostname: 如果 SMTP 在你的本机上,你只需要指定服务器地址为 localhost 即可。

Python SMTP 对象使用 sendmail 方法发送邮件,语法如下:

1
SMTP.sendmail(from_addrto_addrsmsg[mail_optionsrcpt_options]  

参数说明:

  • from_addr: 邮件发送者地址。
  • to_addrs: 字符串列表,邮件发送地址。
  • msg: 发送消息

这里要注意一下第三个参数,msg 是字符串,表示邮件。我们知道邮件一般由标题,发信人,收件人,邮件内容,附件等构成,发送邮件的时候,要注意 msg 的格式。这个格式就是 smtp 协议中定义的格式。

SMTP类还具有如下方法:

1
2
3
4
5
6
7
SMTP.connect([host[,post]])    #smtp
SMTP.login(user,password)    #smtp
SMTP.starttls([keyfile[,certfile]])     #TLSSMTP使gmailsmtp
SMTP.quit()     #SMTP

 

MIME:

MIME,英文全称为“Multipurpose Internet Mail Extensions”,即多用途互联网邮件扩展,是目前互联网电子邮件普遍遵循的邮件技术规范。

 

Python常用的MIME实现类:

1.

1
2
3
4
5
email.mime.multipart.MIMEMultipart([_subtype[,boundary[,_subparts[,_params]]]])   
#MIME_subtype“Content-type:multipart/subtype”mixedrelatedaltermativemixed
#mixed
#related
#alternative  

 

2.

1
2
email.mime:audio.MIMEAudio(_audiodata[,_subtype[,_encoder[,**_params]]])
#_audiodata

 

3.

1
2
email.mime:image.MIMEImage(_imagedata[,_subtype[,_encoder[,**_params]]])
#_imagedata

 

4.

1
2
email.mime.text.MIMEText(_text[,_subtype[,_charset]])
#,_text_subtypeplainhtml

 

 

简单的常用邮件实例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.header import Header
 SMTP 
mail_host = "smtp.163.com"  smtpsmtp.163.com
mail_user = "kurolz@163.com"  
mail_pass = "****"  
sender = 'kurolz@163.com'
receivers = 'hjxzt@qq.com'  
message = MIMEText('This is a Python Test Text')
message['From'] = sender
message['To'] = receivers
subject = 'One Test Mail'
message['Subject'] = Header(subject)
try:
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host25)  # 25  SMTP 
    smtpObj.login(mail_usermail_pass)
    smtpObj.sendmail(senderreceiversmessage.as_string())
    print ("")
except smtplib.SMTPException as e:
    print ("Error: "+str(e))