SMTP模块
这么多已定义的类中,我们最常用的的还是smtplib.SMTP类,就具体看看该类的用法:
smtp实例封装一个smtp连接,它支持所有的SMTP和ESMTP操作指令,如果host和port参数被定义,则smtp会在初始化期间自动调用connect()方法,如果connect()方法失败,则会触发SMTPConnectError异常,timeout参数设置了超时时间。在一般的调用过程中,应该遵connetc()、sendmail()、quit()步骤。
SMTP模块主要方法
下面我们来看看该类的方法:
代码如下:
SMTP.set_debuglevel(level)
设置输出debug调试信息,默认不输出调试信息。
SMTP.docmd(cmd[, argstring])
发送一个command到smtp服务器,
SMTP.connect([host[, port]])
连接到指定的smtp服务器,默认是本机的25端口。也可以写成hostname:port的形式。
SMTP.helo([hostname])
使用helo指令向smtp服务器确认你的身份。
SMTP.ehlo([hostname])
使用ehlo指令向esmtp服务器确认你的身份。
SMTP.ehlo_or_helo_if_needed()
如果在以前的会话连接中没有提供ehlo或者helo指令,这个方法调用ehlo()或者helo()。
SMTP.has_extn(name)
判断指定的名称是否在smtp服务器上。
SMTP.verify(address)
判断邮件地址是否在smtp服务器上存在。
SMTP.login(user, password)
登陆需要验证的smtp服务器,如果之前没有提供ehlo或者helo指令,则会先尝试ESMTP的ehlo指令。
SMTP.starttls([keyfile[, certfile]])
使smtp连接运行在TLS模式,所有的smtp指令都会被加密。
SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options])
发送邮件,该方法需要一些邮件地址和消息。
SMTP.quit()
终止smtp会话并且关闭连接。
经过搜索学习发现网上大多都是用smtp类的sendmail这个方法来发邮件,那就先看看这个例子:
使用sendmail发送邮件
代码如下:
import smtplib
import time
from email.message import Message
from time import sleep
import email.utils
import base64
smtpserver = 'smtp.gmail.com'
username = 'username@gmail.com'
password = 'password '
from_addr = 'from@gmail.com'
to_addr = 'tooooooo@qq.com'
cc_addr = 'ccccccccc@qq.com'
time = email.utils.formatdate(time.time(),True)
message = Message()
message['Subject'] = 'Mail Subject'
message['From'] = from_addr
message['To'] = to_addr
message['Cc'] = cc_addr
message.set_payload('mail content '+time)
msg = message.as_string()
sm = smtplib.SMTP(smtpserver,port=587,timeout=20)
sm.set_debuglevel(1)
sm.ehlo()
sm.starttls()
sm.ehlo()
sm.login(username, password)
sm.sendmail(from_addr, to_addr, msg)
sleep(5)
sm.quit()
Email模块
如果想在邮件中携带附件、使用html书写邮件,附带图片等等,就需要使用email模块及其子模块。下面来看看email包,email包是用来管理email信息的,它包括MIME和其他基于RFC 2822的消息格式。email包的主要特征是在它内部解析和生成email信息是分开的模块来实现的。
新闻热点
疑难解答