码迷,mamicode.com
首页 > 编程语言 > 详细

Python 发送邮件

时间:2016-03-13 07:51:31      阅读:380      评论:0      收藏:0      [点我收藏+]

标签:

ref: 1. http://www.cnblogs.com/xiaowuyi/archive/2012/03/17/2404015.html      2. http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386832745198026a685614e7462fb57dbf733cc9f3ad000

     3.http://www.runoob.com/python/python-email.html

import smtplib
from email.mime.text import MIMEText

sender=easy_install@163.com
user_name=easy_install@163.com
passwd=*****
smtp_server=smtp.163.com


def send_mail(*receivers):
    msg=MIMEText(hello,_subtype=plain,_charset=utf-8)
    
    ‘‘‘
    
    msg=MIMEText(‘<html><body>hello</body></html>‘,
                ‘html‘,‘utf-8‘)
    ‘‘‘

    s=smtplib.SMTP()
    s.connect(smtp_server)
    s.login(user_name,passwd)
    s.sendmail(sender,;.join(receivers),msg.as_string())

if __name__==__main__:
    send_mail(****@163.com)
"""
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage



def sendMail(sender,reciver,subject):
    username="***@163.com"
    password="*****"

    html="""
        <html>
            <body>
                <img src="cid:img">
            </body>
        </html> 

        """
    htm=MIMEText(html,html,utf-8)
    msg.attach(htm)   #添加邮件正文

    
    
    att_htm=MIMEText(hello,plain,utf-8)
    att_htm["Content-Disposition"] = attachment; filename=%s %1.txt
    msg.attach(att_htm)  #添加附件,附件为文本
    
    att_img=MIMEImage(open(/home/lance/1.jpg,rb).read())
    att_img["Content-Disposition"] = attachment; filename=%s %1.jpg
    msg.attach(att_img)  #添加附件,附件为图片

    img=MIMEImage(open(/home/lance/1.jpg,rb).read())
    img["Content-ID"]= "<img>"
    msg.attach(img)     #添加图片,图片显示在正文,不在附件,正文中的 <img src="cid:img">引用
    

    msg[From]="***@163.com"
    msg[To]=";".join(reciver)

    smtp=smtplib.SMTP()
    smtp.connect("smtp.163.com")
    smtp.login(username, password)
    smtp.sendmail(sender, reciver, msg.as_string())
    smtp.quit()

if __name__=="__main__":

    try:
        sendMail(***@163.com, [***@163.com], subject=subject)
        print 发送成功
    except Exception,e:
        print str(e)
msg attach的顺序很重要,先添加邮件正文,其次是附件....

Python 发送邮件

标签:

原文地址:http://www.cnblogs.com/Citizen/p/5271183.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!