Python发送邮件

#-*- coding:gb2312 -*-

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def sendmail(to, sub, content):
    text = MIMEText(content, _subtype='plain', _charset='gb2312')
    
    attachment = MIMEText(open('d:\\server-monitor.zip', 'rb').read(), 'base64', 'gb2312')
    attachment['Content-Type'] = 'application/octet-stream'
    attachment['Content-Disposition'] = 'attachment; filename="server-monitor.rar"'
    
    mailbody = MIMEMultipart()
    mailbody.attach(text)
    mailbody.attach(attachment)
    mailbody['Subject'] = sub
    mailbody['From'] = 'pythonic<username@163.com>'
    mailbody['To'] = to
    
    smtp = smtplib.SMTP()
    #smtp.set_debuglevel(True)
    smtp.connect('smtp.163.com', 25)
    smtp.ehlo()
    smtp.helo('163.com')
    smtp.login('username', 'password')
    smtp.sendmail('pythonic<username@163.com>', to, mailbody.as_string())
    smtp.quit()
    smtp.close()

if __name__ == '__main__':
    sendmail('lichmama@cnblogs.com', 'hello, python!<III>', 'yeah, this is a test mail.\r\ngo checkout the attachment!')

 

文本和附件发送方式示例,参考文档:http://www.cnblogs.com/xiaowuyi/archive/2012/03/17/2404015.html

posted @ 2015-02-28 16:09  lichmama  阅读(243)  评论(0编辑  收藏  举报