(Python)利用SMTP发送邮件进阶篇,发送混合格式邮件

来源:互联网 发布:好看的武侠小说知乎 编辑:程序博客网 时间:2024/06/14 03:04

在(Python)利用SMTP发送邮件基础篇,发送文本邮件中详细讲解了如何发送文本文件,这里讲解如何发送html、附件和图片

html很简单,只要MIMEText中的参数改成html即可

附件也不难,难的是加图片

虽然图片可以当做附件发送,但是显然还需要一个加入正文的功能,方法是用html的img标签把图片加入。但是这样会有个问题,一般的邮箱都会将这种链接屏蔽掉。这个问题有2种解决方法,第一种是先把图片加入到附件,然后再把图片加入正文,第二种是利用MIMEMultipart的三层结构。第一种方法就不能把图片直接加入正文而不加入附件列表,所以我采用第二种。

代码:

#coding=utf-8import smtplibimport jsonfrom email.mime.text import MIMETextfrom email.mime.image  import  MIMEImagefrom email.mime.multipart import MIMEMultiparthost = ''user = ''  #发件人password = ''sender = ''def send_mail(to_list, subject, content,content_type='plain'):    msg_alt = MIMEMultipart('alternative')    msg_rel = MIMEMultipart('related')    msg = MIMEMultipart('mixed')    msg_rel.attach(msg_alt)    msg.attach(msg_rel)    msg['from'] = user    msg['to'] = ','.join(to_list)   #注意,不是分号    msg['subject'] = subject    if(content_type == 'plain'):        for type,item in content:            if type == 'text':                text = MIMEText(item,'plain','utf-8')                msg_alt.attach(text)            elif type == 'attach_path':                attachment = get_attach(item)                if(attachment):                    msg.attach(attachment)            else:                #print('type error')                pass    elif content_type == 'html':        mailBody = ''        for type,item in content:            if type == 'html':                mailBody += item            elif type == 'image_path':                image = get_image(item)                if(image):                    con = '<p><img src=cid:'+ item +'></p>'                    mailBody = mailBody + con                    msg_rel.attach(image)            elif type == 'attach_path':                attachment = get_attach(item)                if(attachment):                    msg.attach(attachment)            else:                #print('type error')                pass        html = MIMEText(mailBody,'html','utf-8')        msg_alt.attach(html)    else:        return False    server = smtplib.SMTP()    #server.set_debuglevel(1)    try:        server.connect(host,25)    except:        print('connect fail')    try:        server.ehlo(user)        server.login(user,password)        print('login ok')    except:        print('login fail')    try:        server.sendmail(sender, to_list, str(msg))        server.close()        return True    except OSError:        print('OSError')        return False    except:        print('unexpect error')        return False#添加图片内容到正文def get_image(image_path):    try:        fp = open(image_path,'rb')    except:        return None    image = MIMEImage(fp.read())    fp.close()    image.add_header( 'Content-ID' ,  '<'+image_path+'>' )    return image#添加附件def get_attach(attach_path):    try:        f = open(attach_path,'rb')        att = MIMEText(f.read(),'base64', 'utf-8')        f.close()    except FileNotFoundError:        print('FileNotFound')        return None    except:        print('unexpect error')        return None    att['Content-Type'] = 'application/octet-stream'    att['Content-Disposition'] = 'attachment; filename='+attach_path    return attdef analysis(json_arg):    arg = json.loads(json_arg)    to_list = arg['to_list']    subject = arg['subject']    content = arg['content']    content_type = 'plain'    try:        content_type = arg['content_type']    except:        pass    return def test1():    recv = ['']    content = (('text','这不是垃圾邮件啊啊啊啊啊'),('attach_path','1.txt'))    arg1 = {'to_list':recv, 'subject':'test', 'content':content}    json_arg = json.dumps(arg1)    if(analysis(json_arg)):        print('send ok')    else:        print('send fail')def test2():    recv = ['']    html = '<a href="http://www.baidu.com">百度链接</a>'    content = (('html' ,'看图'),('attach_path','1.txt'),('image_path','1.jpg'),('image_path','2.png'),('html',html))  #html的值不一定非要html代码,普通字符串也行    arg2 = {'to_list':recv, 'subject':'test', 'content':content,'content_type':'html'}    json_arg = json.dumps(arg2)    if(analysis(json_arg)):        print('send ok')    else:        print('send fail')if __name__ == '__main__':    test1()    test2()'''send_mail.py接口说明:函数analysis(json_arg)只有1个参数,json_arg是json类型,元素有3-4个4个元素的键依次是to_list,subject,content,content_type(1)to_list是收件人列表,是列表类型,其中每个元素(至少1个元素)都是字符串,对应一个邮箱地址(2)subject是邮件标题,是字符串类型(3)content是元祖类型,每个元素(type,item)是邮件正文中的1个内容,type是'text'或'html'或'attach_path'或'image_path',对应的item(都是字符串)分别代表文本、html代码、附件名、图片名(如果需要的话前面带上路径名)(4)content_type是'plain'或'html',如果是'plain'(可以缺省)那么content是'text'或'attach_path',如果是'html'那么content是'html'或'attach_path'或'image_path''''

原创粉丝点击