很多时候我们在使用python脚本时需要发送邮件,这里我写了一个简单的邮件发送脚本
功能:
支持邮件主题,发件人,接收人的定义
支持发送text/html格式邮件
支持发送带附件的邮件(根据参数自动识别)
代码如下:
-
#!/usr/bin/env python
-
#coding:utf-8
-
import os,sys
-
import re
-
import smtplib
-
import email.utils
-
import email.MIMEMultipart
-
import email.MIMEText
-
import email.MIMEBase
-
-
def sendMail(Subject,Body,mailTo=['邮件接收人邮箱1','邮件接收人邮箱2'],file_name='None',bodyType='text'):
-
mailFrom=('邮件发件人名称','发件人邮箱地址')
-
-
mailSubject=Subject
-
if bodyType=='text':
-
msg=email.MIMEText.MIMEText(Body,'plain','utf-8')
-
else:
-
msg=email.MIMEText.MIMEText(Body,'html','utf-8')
-
-
bodyMsg=email.MIMEMultipart.MIMEMultipart()
-
bodyMsg.attach(msg)
-
if file_name != 'None' and os.path.isfile(file_name):
-
contype='application/octet-stream'
-
maintype,subtype = contype.split('/', 1)
-
data = open(file_name,'rb')
-
file_msg = email.MIMEBase.MIMEBase(maintype,subtype)
-
file_msg.set_payload(data.read())
-
data.close()
-
email.Encoders.encode_base64(file_msg)
-
basename = os.path.basename(file_name)
-
file_msg.add_header('Content-Disposition','attachment', filename = basename)
-
bodyMsg.attach(file_msg)
-
-
-
#bodyMsg['To']=email.utils.formataddr(mailTo)
-
bodyMsg['From']=email.utils.formataddr(mailFrom)
-
bodyMsg['Subject']=mailSubject
-
bodyMsg['Date']=email.utils.formatdate()
-
-
server=smtplib.SMTP('邮件服务器地址')
-
username='用户名'
-
password='密码'
-
-
try:
-
server.ehlo()
-
server.login(username,password)
-
server.sendmail(mailFrom[1],mailTo,bodyMsg.as_string())
-
finally:
-
server.quit()
-
if __name__=='__main__':
-
Subject='这是一个测试邮件'
-
Body='测试邮件'
-
file_name='urllist.txt'
-
sendMail(Subject,Body,file_name)
-
#sendMail(Subject,Body)
阅读(2401) | 评论(0) | 转发(0) |