smtp 邮件发送

来源:互联网 发布:爱名网域名注册 编辑:程序博客网 时间:2024/05/16 19:03
#!/usr/bin/python
# -*- coding: UTF-8 -*-

import smtplib
from email.mime.text import MIMEText  
from email.mime.multipart import MIMEMultipart

sender='liuyangjun@zjcap.cn'
receivers=['liuyangjun@zjcap.cn']


#第一种  输出一般 text 格式文本
#message = """From: <liuyangjun@zjcap.cn>
#To: <liuyangjun@zjcap.cn>
#Subject: SMTP e-mail test
#
#This is a test e-mail message.
#"""


#第二种  输出 html 格式的文本
#msg = MIMEText('This is a test e-mail message.',_subtype='html',_charset='gb2312')
#msg['Subject'] = 'SMTP e-mail test'
#msg['From'] = 'liuyangjun@zjcap.cn'
#msg['To'] = ";".join(receivers)

#第三种  带附件的邮件发送
#创建一个带附件的实例
msg = MIMEMultipart()
#构造附件1
att1 = MIMEText(open('/tmp/123.txt', 'rb').read(), 'base64', 'gb2312')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename="123.txt"'#这里的filename可以任意写,写什么名字,邮件中显示什么名字
msg.attach(att1)

#构造文字附件
att2 = MIMEText("乔装打扮,不择手段")
msg.attach(att2)

msg['Subject'] = 'SMTP e-mail test'
msg['From'] = 'liuyangjun@zjcap.cn'
msg['To'] = ";".join(receivers)

mail_host='smtp.exmail.qq.com'
mail_user='liuyangjun@zjcap.cn'
mail_pass='Lyj!2015'
try:
  smtpObj = smtplib.SMTP()
  smtpObj.connect(mail_host)
  smtpObj.login(mail_user, mail_pass)
  #第一种
  #smtpObj.sendmail(sender, receivers, msg)
  #第二种 第三种
  smtpObj.sendmail(sender, receivers, msg.as_string())
  smtpObj.close()
except Exception as e:
  print(str(e))
0 0