python基础教程之支持smtp身份验证的邮件发送

发布时间:2019-10-19编辑:脚本学堂
本文介绍了python基础教程中的一个例子,一个支持smtp身份验证的邮件发送代码,有关python邮件发送的实现方法,有需要的朋友参考下。

例子,python邮件发送,支持smtp身份验证。

代码:
 

复制代码 代码示例:

import sys, smtplib, mimewriter, base64, stringio, os, string, time
 
from email.mimemultipart import mimemultipart
from email.mimebase import mimebase
from email.mimetext import mimetext
from email.utils import commaspace, formatdate
from email import encoders

def send_mail(send_from, send_to, subject, text, files=[],
              server="localhost", user = none, password = none):
 
  assert type(send_to)==list
  assert type(files)==list
 
  msg = mimemultipart()
  msg['from'] = send_from
  msg['to'] = commaspace.join(send_to)
  msg['date'] = formatdate(localtime=true)
  msg['subject'] = subject
 
  msg.attach( mimetext(text) )
 
  for file in files:
    part = mimebase('application', "octet-stream")
    part.set_payload( open(file,"rb").read() )
    encoders.encode_base64(part)
    part.add_header('content-disposition', 'attachment; filename="%s"' % os.path.basename(file))
    msg.attach(part)
 
  smtp = smtplib.smtp(server)
  if (user != none):
    smtp.ehlo()
    smtp_userid64 = base64.encodestring(user)
    smtp.docmd("auth", "login " + smtp_userid64[:-1])
    if password != none:
      smtp_pass64 = base64.encodestring(password)
      smtp.docmd(smtp_pass64[:-1])
 
  smtp.sendmail(send_from, send_to, msg.as_string())
  smtp.close()
 
# 测试python邮件发送
#test_smtp.py
from smtp import *
 
send_mail('jbxue1@163.com',
         ['jbxue2@gmail.com', 'jbxue2@163.com'],
          u'标题:来自jb200.com的测试邮件',
          u'内容:一寸光阴一寸金',
          [r'/home/jbxue/附件1.txt'],
          'smtp.163.com', 'user', 'pass')