很多时候我们在使用python脚本时需要发送邮件,这里我写了一个简单的邮件发送脚本
功能:
  支持邮件主题,发件人,接收人的定义
  支持发送text/html格式邮件
  支持发送带附件的邮件(根据参数自动识别)
代码如下:

点击(此处)折叠或打开

  1. #!/usr/bin/env python
  2. #coding:utf-8
  3. import os,sys
  4. import re
  5. import smtplib
  6. import email.utils
  7. import email.MIMEMultipart
  8. import email.MIMEText
  9. import email.MIMEBase

  10. def sendMail(Subject,Body,mailTo=['邮件接收人邮箱1','邮件接收人邮箱2'],file_name='None',bodyType='text'):
  11.    mailFrom=('邮件发件人名称','发件人邮箱地址')

  12.    mailSubject=Subject
  13.    if bodyType=='text':
  14.        msg=email.MIMEText.MIMEText(Body,'plain','utf-8')
  15.    else:
  16.        msg=email.MIMEText.MIMEText(Body,'html','utf-8')

  17.    bodyMsg=email.MIMEMultipart.MIMEMultipart()
  18.    bodyMsg.attach(msg)
  19.    if file_name != 'None' and os.path.isfile(file_name):
  20.        contype='application/octet-stream'
  21.        maintype,subtype = contype.split('/', 1)
  22.        data = open(file_name,'rb')
  23.        file_msg = email.MIMEBase.MIMEBase(maintype,subtype)
  24.        file_msg.set_payload(data.read())
  25.        data.close()
  26.        email.Encoders.encode_base64(file_msg)
  27.        basename = os.path.basename(file_name)
  28.        file_msg.add_header('Content-Disposition','attachment', filename = basename)
  29.        bodyMsg.attach(file_msg)

  30.          
  31.    #bodyMsg['To']=email.utils.formataddr(mailTo)
  32.    bodyMsg['From']=email.utils.formataddr(mailFrom)
  33.    bodyMsg['Subject']=mailSubject
  34.    bodyMsg['Date']=email.utils.formatdate()

  35.    server=smtplib.SMTP('邮件服务器地址')
  36.    username='用户名'
  37.    password='密码'

  38.    try:
  39.        server.ehlo()
  40.        server.login(username,password)
  41.        server.sendmail(mailFrom[1],mailTo,bodyMsg.as_string())
  42.    finally:
  43.        server.quit()
  44. if __name__=='__main__':
  45.    Subject='这是一个测试邮件'
  46.    Body='测试邮件'
  47.    file_name='urllist.txt'
  48.    sendMail(Subject,Body,file_name)
  49.    #sendMail(Subject,Body)

12-17 04:44