zoukankan      html  css  js  c++  java
  • python实现的使用gmail发邮件的代码段

    找到个用python写的使用gmail发邮件的代码,挺好用的,当然错误处理都没做,先记录下来:
    View Code
     1 import os
     2 import smtplib
     3 import mimetypes
     4 from email.MIMEMultipart import MIMEMultipart
     5 from email.MIMEBase import MIMEBase
     6 from email.MIMEText import MIMEText
     7 from email.MIMEAudio import MIMEAudio
     8 from email.MIMEImage import MIMEImage
     9 from email.Encoders import encode_base64
    10 
    11 def sendMail(subject, text, *attachmentFilePaths):
    12   gmailUser = 'youraccount@gmail.com'
    13   gmailPassword = 'yourpasswd'
    14   recipient = 'mail1@gmail.com;mail2@gmail.com'
    15 
    16   msg = MIMEMultipart()
    17   msg['From'] = gmailUser
    18   msg['To'] = recipient
    19   msg['Subject'] = subject
    20   msg.attach(MIMEText(text))
    21 
    22   for attachmentFilePath in attachmentFilePaths:
    23     msg.attach(getAttachment(attachmentFilePath))
    24 
    25   mailServer = smtplib.SMTP('smtp.gmail.com', 587)
    26   mailServer.ehlo()
    27   mailServer.starttls()
    28   mailServer.ehlo()
    29   mailServer.login(gmailUser, gmailPassword)
    30   mailServer.sendmail(gmailUser, recipient, msg.as_string())
    31   mailServer.close()
    32 
    33   print('Sent email to %s' % recipient)
    34 
    35 def getAttachment(attachmentFilePath):
    36   contentType, encoding = mimetypes.guess_type(attachmentFilePath)
    37 
    38   if contentType is None or encoding is not None:
    39     contentType = 'application/octet-stream'
    40 
    41   mainType, subType = contentType.split('/', 1)
    42   file = open(attachmentFilePath, 'rb')
    43 
    44   if mainType == 'text':
    45     attachment = MIMEText(file.read())
    46   elif mainType == 'message':
    47     attachment = email.message_from_file(file)
    48   elif mainType == 'image':
    49     attachment = MIMEImage(file.read(),_subType=subType)
    50   elif mainType == 'audio':
    51     attachment = MIMEAudio(file.read(),_subType=subType)
    52   else:
    53     attachment = MIMEBase(mainType, subType)
    54   attachment.set_payload(file.read())
    55   encode_base64(attachment)
    56 
    57   file.close()
    58 
    59   attachment.add_header('Content-Disposition', 'attachment',   filename=os.path.basename(attachmentFilePath))
    60   return attachment
  • 相关阅读:
    UVA 562 Dividing coins
    who is in front of me 解题报告
    UVA 111 历史考试
    UVA 1045 最长公共子序列
    HDU 1003 解题报告
    ACM2014-04训练计划
    基于邻接表的新顶点的增加
    4004.六度空间理论
    4003.基于Dijsktra算法的最短路径求解
    4002.基于快排思想的查找
  • 原文地址:https://www.cnblogs.com/liupengblog/p/2550238.html
Copyright © 2011-2022 走看看