python发送邮件(无附件)
=======================================================
#!/usr/bin/env python
#coding=utf-8
import smtplib
from email.mime.text import MIMEText
from email.header import Header
def sendmail():
#第三方服务(发件人的信息)
mail_host = '设置服务器:端口'
mail_user = '发件人邮箱的用户名'
mail_pass = '发件人邮箱的密码'
receivers = ['接收的邮箱']
#邮件主题
message = MIMEText('你好,邮件测试','plain','utf-8')
message['From'] = Header('发件人的中文名称','utf-8')
message['To'] = Header('收件人的中文名称','utf-8')
# 邮件标题
subject = 'Python 邮件测试'
message['Subject'] = Header(subject,'utf-8')
try:
smtpObj = smtplib.SMTP(mail_host)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login(mail_user,mail_pass)
smtpObj.sendmail(mail_user,receivers,message.as_string())
smtpObj.quit()
print "邮件发送成功"
except smtplib.SMTPException:
print "Error 无法发送邮件"
if __name__ == '__main__':
sendmail()
========================================================
python发送邮件(有附件)
#!/usr/bin/env python
#coding=utf-8
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
def sendmail():
#第三方服务
mail_host = '设置服务器:端口'
mail_user = '发件人邮箱的用户名'
mail_pass = '发件人邮箱的密码'
receivers = ['接收的邮箱']
message = MIMEMultipart()
message['From'] = Header('发件人邮箱的中文名称','utf-8')
message['To'] = Header('收件人邮箱的中文名称','utf-8')
#邮件标题
subject = 'Python 邮件测试'
message['Subject'] = Header(subject,'utf-8')
# 邮件正文内容
message.attach(MIMEText('这是菜鸟教程Python 邮件发送测试……','plain','utf-8'))
# 构造附件1,传送当前目录下的 bj.log 文件
att1 = MIMEText(open('bj.log', 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写,写什么名字,邮件中显示什么名字(也就是附件的名称)
att1["Content-Disposition"] = 'attachment; filename="test.txt"'
message.attach(att1)
try:
smtpObj = smtplib.SMTP(mail_host)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login(mail_user,mail_pass)
smtpObj.sendmail(mail_user,receivers,message.as_string())
smtpObj.quit()
print "邮件发送成功"
except smtplib.SMTPException:
print "Error 无法发送邮件"
if __name__ == '__main__':
sendmail()