Python 下smtplib模块
程序员文章站
2022-07-10 15:25:32
...
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2016/10/14 17:59
# @Author : Beam
# @Site :
# @File : demo_sendmail.py
# @Software: PyCharm
import smtplib
import string
def sendMail(text):
HOST = 'smtp.126.com' ##定义SMTP主机
SUBJECT = 'Test email from python' ##邮件主题
TO = ['[email protected]','[email protected]'] ##收件地址
FROM = '[email protected]' ##发件地址
BODY =string.join(("From: %s" %FROM,"To: %s" % TO, "Subject: %s" % SUBJECT,"",text),"\r\n") ##组装sendmail方法的邮件主题内容,每段内容以\r\n进行分隔
try:
server = smtplib.SMTP() ##创建smtp()对象
server.connect(HOST,25) ##通过connenct方法链接smtp主机
server.starttls() ##启动安全传输模式
server.login("[email protected]",passwd) ##邮箱账号登录校验
server.sendmail(FROM,TO,BODY) ##邮件发送
server.quit() ##断开smtp链接
return True
except Exception,e:
print "失败:" + str(e)
return False
def main():
text = 'Python rules them all!' ##邮件内容
sendMail(text)
if __name__ == '__main__':
main()