设为首页 收藏本站
查看: 808|回复: 0

[经验分享] python实例26[sendemail]

[复制链接]

尚未签到

发表于 2015-4-26 09:37:53 | 显示全部楼层 |阅读模式
  
  一 发送简单的纯文本邮件


import sys
import os.path
import smtplib
import email
def sendTextMail(mailhost,sender,recipients,ccto = '',bccto = '',subject = '',message = '', messagefile = ''):
  try:
    mailport=smtplib.SMTP(mailhost)
  except:
    sys.stderr.write('Unable to connect to SMTP host "' + mailhost \
                      + '"!\nYou can try again later\n')
    return 0
   
  if(os.path.exists(messagefile) and os.path.isfile(messagefile)):
    with open(messagefile,'r') as f:
      message += f.read()
   
  fullmessage = 'From: ' + '  \n' +\
              'To: ' + recipients + '\n' +\
              'CC: '+ ccto + '\n' +\
              'Bcc: ' + bccto + '\n' +\
              'Subject: ' + subject + '\n' +\
              'Date: ' + email.Utils.formatdate() +'\n' +\
              '\n' +\
              message
  try:
    #mailport.set_debuglevel(1)
    allrecipients = recipients.split(',')
    if not ccto == '':
      allrecipients.extend(ccto.split(','))
    if not bccto == '':
      allrecipients.extend(bccto.split(','))
    #print allrecipients
    #allrecipients must be list type
    failed = mailport.sendmail(sender, allrecipients, fullmessage)
  except Exception as e:
    sys.stderr.write(repr(e))
    return 0
  finally:
    mailport.quit()
   
  return 1  
  
  注意:
  recipients,ccto,bccto是接收者的邮件地址,多个地址间使用,分割;
  message = '', messagefile = ''表示要发送的email的内容,为可选参数,messagefile表示email的内容来自一个文本文件;
  mailport.sendmail(sender, recipients, message)中,message中的from/to/bcc等只是用来email的显示,真正的收件人必须通过recipients来传入,recipients必须为收件人的email地址的数组,
  
  二 发送html的邮件


import sys
import os.path
import smtplib
import email
from email import encoders
import mimetypes
from email.mime.base import MIMEBase
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def getMIMEObj(path):
    ctype, encoding = mimetypes.guess_type(path)
    if ctype is None or encoding is not None:
        # No guess could be made, or the file is encoded (compressed), so
        # use a generic bag-of-bits type.
        ctype = 'application/octet-stream'
    maintype, subtype = ctype.split('/', 1)
    msg = None
    #print maintype
    #print subtype
    if maintype == 'text':
        fp = open(path)
        # Note: we should handle calculating the charset
        msg = MIMEText(fp.read(), _subtype=subtype, _charset='utf-8')
        fp.close()
    elif maintype == 'image':
        fp = open(path, 'rb')
        msg = MIMEImage(fp.read(), _subtype=subtype)
        fp.close()
    elif maintype == 'audio':
        fp = open(path, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=subtype)
        fp.close()
    else:
        fp = open(path, 'rb')
        msg = MIMEBase(maintype, subtype)
        msg.set_payload(fp.read())
        fp.close()
        # Encode the payload using Base64
        encoders.encode_base64(msg)
    # Set the filename parameter
    msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(path))
    return msg
  
def sendHtmlMail(mailhost,subject,sender,recipients,ccto = '',bccto = '',htmldir = '', htmlfile = ''):
  try:
    mailport=smtplib.SMTP(mailhost)
  except:
    sys.stderr.write('Unable to connect to SMTP host "' + mailhost \
                      + '"!\nYou can try again later\n')
    return 0
   
  msgroot = MIMEMultipart('related')
  msgroot['From'] = sender
  msgroot['To'] = recipients
  msgroot['Cc'] = ccto
  msgroot['Bcc'] = bccto
  msgroot['Subject'] = subject
  msghtml = MIMEMultipart('alternative')
  msgroot.attach(msghtml)  
  if os.path.exists(os.path.join(htmldir,htmlfile)):
    htmlf = open(os.path.join(htmldir,htmlfile))
    htmlmessage = MIMEText(htmlf.read(),'html','utf-8')
    htmlf.close()
    msghtml.attach(htmlmessage)
   
  for root, subdirs, files in os.walk(htmldir):
    for file in files:
      if file == htmlfile:
        continue
      else:
        msgroot.attach(getMIMEObj(os.path.join(root,file)))
  
  failed = 0
  try:
    #mailport.set_debuglevel(1)
    allrecipients = recipients.split(',')
    if not ccto == '':
      allrecipients.extend(ccto.split(','))
    if not bccto == '':
      allrecipients.extend(bccto.split(','))
    #print allrecipients
    failed = mailport.sendmail(sender, allrecipients, msgroot.as_string())
    print failed
  except Exception as e:
    sys.stderr.write(repr(e))
  finally:
    mailport.quit()
   
  return failed  
  
  注意:
  htmldir参数表示要发送的html文件所在的目录,此目录下仅包含html文件和html文件引用的相关文件,且所有引用的文件必须与html都在同一目录下,不能有子目录;
  htmlfile参数表示要显示到email中的html文件;
  
  例如:
  有html文件如下:
  d:\html
  |--myhtmlemail.html
  |--mylinkedtext.txt
  |--myimage.gif
  
  且myhtmlemail.html的内容为:
  
  
message1

This is HTML email sent by python



  
  则收到的email如下:
DSC0000.png
  
  
  三 使用如下:
  mailhost = 'mail-relay.example.com'
sender  = "AAA@example.com"
recipients = "BBB@example.com,EEE@example.com"
ccto = 'CCC@example.com'
bccto = 'DDD@example.com'
subject = "Testing1"
message = "Testing!\nTesting!\n"
messagefile = "mymessage.txt"
htmldir = 'D:\\html'
htmlfile = 'myhtmleamil.html'
         
sendTextMail(mailhost,sender,recipients,ccto,bccto,subject,message,messagefile)
sendHtmlMail(mailhost, subject,sender,recipients,htmldir=htmldir,htmlfile=htmlfile)
  
  四 发送带有附件的email


import sys
import os.path
import smtplib
import email  
import mimetypes
from email import encoders
from email.mime.base import MIMEBase
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def getMIMEObj(path):
    ctype, encoding = mimetypes.guess_type(path)
    if ctype is None or encoding is not None:
        # No guess could be made, or the file is encoded (compressed), so
        # use a generic bag-of-bits type.
        ctype = 'application/octet-stream'
    maintype, subtype = ctype.split('/', 1)
    msg = None
    #print maintype
    #print subtype
    if maintype == 'text':
        fp = open(path)
        # Note: we should handle calculating the charset
        msg = MIMEText(fp.read(), _subtype=subtype, _charset='utf-8')
        fp.close()
    elif maintype == 'image':
        fp = open(path, 'rb')
        msg = MIMEImage(fp.read(), _subtype=subtype)
        fp.close()
    elif maintype == 'audio':
        fp = open(path, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=subtype)
        fp.close()
    else:
        fp = open(path, 'rb')
        msg = MIMEBase(maintype, subtype)
        msg.set_payload(fp.read())
        fp.close()
        # Encode the payload using Base64
        encoders.encode_base64(msg)
    # Set the filename parameter
    msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(path))
    return msg
  
def sendMail(mailhost,subject,sender,recipients,ccto = '',bccto = '',message = '', payloads = ''):
  try:
    mailport=smtplib.SMTP(mailhost)
  except:
    sys.stderr.write('Unable to connect to SMTP host "' + mailhost \
                      + '"!\nYou can try again later\n')
    return 0
   
  msgroot = MIMEMultipart('mixed')
  msgroot['From'] = sender
  msgroot['To'] = recipients
  msgroot['Cc'] = ccto
  msgroot['Bcc'] = bccto
  msgroot['Subject'] = subject
  alternative = MIMEMultipart('alternative')
  msgroot.attach(alternative)  
  mes = MIMEText(message,'plain','utf-8')
  alternative.attach(mes)
   
  for file in payloads.split(','):
      if os.path.isfile(file) and os.path.exists(file):
        msgroot.attach(getMIMEObj(file))
      else:
        sys.stderr.write("The file %s cannot be found" % file)
  
  try:
    #mailport.set_debuglevel(1)
    allrecipients = recipients.split(',')
    if not ccto == '':
      allrecipients.extend(ccto.split(','))
    if not bccto == '':
      allrecipients.extend(bccto.split(','))
    #print allrecipients
    failed = mailport.sendmail(sender, allrecipients, msgroot.as_string())
    if failed == None:
      sys.stderr.write(failed)
      return 0
  except Exception as e:
    sys.stderr.write(repr(e))
    return 0
  finally:
    mailport.quit()
   
  return 1

mailhost = 'mail-relay.company.com'
sender  = "AAA@Company.com"
recipients = "BBB@company.com"
ccto = 'CCC@company.com'
bccto = 'DDD@company.com'
subject = "Testing1"
message = "Testing!\nTesting!\n"     
sendMail(mailhost,subject,sender,recipients,message = message,payloads = 'c:\\test\\test.ba,C:\\test\s7\\mytable.txt')  
  参考:
  http://canofy.javaeye.com/blog/265600
  http://docs.python.org/library/email-examples.html
  http://www.iyunv.com/itech/archive/2011/02/18/1958114.html
  
  完!

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-60774-1-1.html 上篇帖子: python处理.xml文件工具包之XML2Dict 下篇帖子: 【转载】在Windows环境下用Editplus打造一个Python编辑调试环境
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表