python实现的使用gmail发邮件的代码段
2012-06-15 09:48
507 查看
找到个用python写的使用gmail发邮件的代码,挺好用的,当然错误处理都没做,先记录下来:
View Code
View Code
import os import smtplib import mimetypes from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.MIMEAudio import MIMEAudio from email.MIMEImage import MIMEImage from email.Encoders import encode_base64 def sendMail(subject, text, *attachmentFilePaths): gmailUser = 'youraccount@gmail.com' gmailPassword = 'yourpasswd' recipient = 'mail1@gmail.com;mail2@gmail.com' msg = MIMEMultipart() msg['From'] = gmailUser msg['To'] = recipient msg['Subject'] = subject msg.attach(MIMEText(text)) for attachmentFilePath in attachmentFilePaths: msg.attach(getAttachment(attachmentFilePath)) mailServer = smtplib.SMTP('smtp.gmail.com', 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(gmailUser, gmailPassword) mailServer.sendmail(gmailUser, recipient, msg.as_string()) mailServer.close() print('Sent email to %s' % recipient) def getAttachment(attachmentFilePath): contentType, encoding = mimetypes.guess_type(attachmentFilePath) if contentType is None or encoding is not None: contentType = 'application/octet-stream' mainType, subType = contentType.split('/', 1) file = open(attachmentFilePath, 'rb') if mainType == 'text': attachment = MIMEText(file.read()) elif mainType == 'message': attachment = email.message_from_file(file) elif mainType == 'image': attachment = MIMEImage(file.read(),_subType=subType) elif mainType == 'audio': attachment = MIMEAudio(file.read(),_subType=subType) else: attachment = MIMEBase(mainType, subType) attachment.set_payload(file.read()) encode_base64(attachment) file.close() attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachmentFilePath)) return attachment
相关文章推荐
- c#使用Gmail发邮件实现--推荐
- 二种python发送邮件实例讲解(python发邮件附件可以使用email模块实现)
- 二种python发送邮件实例讲解(python发邮件附件可以使用email模块实现)
- python使用smtplib模块通过gmail实现邮件发送的方法
- python实现SMTP发邮件(不需要注册邮箱使用邮箱的SMTP服务)
- python使用smtplib模块通过gmail实现邮件发送的方法
- 使用python实现http及ftp服务进行数据传输的方法
- python实现清华大学联网助手(一)——urllib/hashlib/getopt/time/codecs的使用
- Python使用time模块实现指定时间触发器示例
- 使用 Python 模块 re 实现解析小工具
- 使用python实现短信PDU编码
- python使用SimpleXMLRPCServer实现简单的rpc
- 使用Python实现博客上进行自动翻页
- 使用python脚本语言实现快速打包
- mac使用python实现网页截图
- 使用Python实现子区域数据分类统计
- 使用Python实现子区域数据分类统计
- [python]使用gevent实现并行登录路由器
- PythonStock(5):使用 dataTable+python 实现服务端多字段排序