zoukankan      html  css  js  c++  java
  • python测试开发django(28)--发送附件EmailMessage

    前言

    Django的send_mail()和send_mass_mail()函数事实上是对EmailMessage类使用方式的一个轻度封装。send_mail()和相关的其他封装函数并没有充分使用EmailMessage类的所有特性。

    要想使用更多特性,比如暗送(BCC),加入附件,或是多用途格式(multi-part)邮件,都要直接创建EmailMessage实例。

    有些资料用的EmailMultiAlternatives类,有些用的EmailMessage类,这2个其实有关联,EmailMultiAlternatives类继承了EmailMessage类

    EmailMessage

    EmailMessage类使用下列参数初始化(除非使用位置参数,否则默认顺序如下)。所有参数均可选,均可在调用send()方法之前的任何时间对其赋值。

    •  subject:邮件的标题行
    • body:邮件的主体内容文本,须是纯文本信息。
    • from_email:发送者的地址。fred@example.com 或 Fred fred@example.com 格式都是合法的。如果忽略该参数,Django就会使用 DEFAULT_FROM_EMAIL 配置项。
    • to:收件人地址列表或元组。
    • bcc:发送邮件时用于“Bcc”头信息的一组列表或元组,也就是暗送的收件人。
    • connection:一个邮件后端实例。用同一个链接发送多封邮件就要用到该参数。忽略该参数时,会在调用send()时自动创建一个新链接。
    • attachments:置于邮件报文内的附件列表。列表元素可以是email.MIMEBase.MIMEBase 实例,也可以是(filename, content, mimetype) 三部分构成的元组。
    • headers:置于邮件报文内的其他头信息(header)的字典。字典的key是头信息的名称,字典的value是头信息的值。这样做能确保头信息的名称和对应值会以正确的格式保存于邮件报文中。
    • cc:发送邮件时放与"Cc"头信息的一系列列表或元组。
    • reply_to:发送电子邮件时"回复"标题中使用的收件人地址列表或元组。
    class EmailMessage:
        """A container for email information."""
        content_subtype = 'plain'
        mixed_subtype = 'mixed'
        encoding = None     # None => use settings default
    
        def __init__(self, subject='', body='', from_email=None, to=None, bcc=None,
                     connection=None, attachments=None, headers=None, cc=None,
                     reply_to=None):
            ...省略
    
        def send(self,fail_silently=False) :
             """
             发送邮件报文。如果在构造邮件时如果指定了某个链接(connection),就会使用该链接发邮件。 否则,就会使用默认后端的实例发邮件。
              如果关键字参数 fail_silently 为 True ,就会忽略邮件发送时抛出的异常。
             """
        def recipients(self):
            """
             返回邮件中所有收件人的列表,不管收件人是在 to 还是 bcc 属性中。
             这是另一个经常被继承覆写的方法, 因为SMTP服务器在发送邮件报文时,要接收完整的收件人列表。
             即使你自己的类使用其他方式来指定收件人,也仍然需要使用该方法返回收件人列表。
            """
    
        def message(self) :
             """
             构造了一个 django.core.mail.SafeMIMEText 对象 (Python的 email.MIMEText.MIMEText 类的子类) 或是 django.core.mail.SafeMIMEMultipart 对象(该对象保存即将发送出去邮件报文)。
             如需扩展 EmailMessage类,一般情况下要覆写该方法,将你所需的内容添加到MIME对象中。
             """
    
       def attach(self, filename=None, content=None, mimetype=None):
            """
             传递一个单独的 email.MIMEBase.MIMEBase 实例做为参数。该实例会直接添加到最终的邮件报文中。
    
             或者,给 attach() 传递三个参数: filename, content 和 mimetype. filename 是出现在邮件中的附件文件的名称, content 是附件的内容,而 mimetype 是附件所使用的MIME类型。 
             如果忽略 mimetype, Django会自动根据附件文件名来推测MIME内容类型。
             例如:
                     message.attach('design.png', img_data, 'image/png')
            """
        
    
         def attach_file(self, path, mimetype=None):
             """
             使用当前文件系统下的某个文件做为附件。调用时,传入某个文件的完整路径,以及该附件的MIME类型(可选的)。
             忽略MIME类型的话,Django会自动根据附件文件名来推测MIME类型。
             最简单的用法如下:
             message.attach_file('/images/weather_map.png')
            """
    

    attach_file方法传文件

    使用当前文件系统下的某个文件作为附件。调用时,传入某个文件的完整路径,这种方法是最简单的,上传本地的某个文件。

    如在templates目录下有一个a.png的图片(图片和其它文件都一样,如xx.doc,只是后缀不一样)

    views.py文件实现代码

    #coding:utf-8
    
    from django.http import HttpResponse
    from django.core.mail import EmailMessage
    import os
    
    def file_mail(request):
        '''发送附件'''
        email = EmailMessage(
            'Hello',
            'Body goes here',
            '3713505@qq.com',   # 发件人
            ['15521040@163.com'],   # 收件人
            ['3719505@qq.com'],                      # cc抄送
            reply_to=['3719505@qq.com'],  # “回复”标题中使用的收件人地址列表或元组
            headers={'Message-ID': 'foo'},
        )
        cur = os.path.dirname(os.path.realpath(__file__))
        # templates目录下有个a.png的图片
        filepath = os.path.join(cur, "templates", "ab.png")
    
        email.attach_file(filepath, mimetype=None)
        email.send()
        return HttpResponse('邮件发送成功,收不到就去垃圾箱找找吧!')
    

      邮件收到效果如下

     attach方法

    attach() 传递三个参数:filename,content和mimetype。filename是出现在邮件中的附件文件的名称,content是附件的内容,而mimetype是附件所使用的MIME类型。

    参考格式如:message.attach('a.png',img_data,'image/png')

    #coding:utf-8
    
    
    from django.http import HttpResponse
    from django.core.mail import EmailMessage
    import os
    
    def file_mail(request):
        '''发送附件'''
        email = EmailMessage(
            'Hello',
            'Body goes here',
            '3733505@qq.com',   # 发件人
            ['15521040@163.com'],   # 收件人
            ['3733505@qq.com'],                      # cc抄送
            reply_to=['15521040@163.com'],  # “回复”标题中使用的收件人地址列表或元组
            headers={'Message-ID': 'foo'},
        )
        cur = os.path.dirname(os.path.realpath(__file__))
        # templates目录下有个a.png的图片
        filepath = os.path.join(cur, "templates", "ab.png")
        #方法1 attach_file
        email.attach_file(filepath, mimetype=None)
    
        #方法2 attach
        filepath1=os.path.join(cur,"templates","c.png")
        img_datas=open(filepath1,"rb")
        email.attach('c.png',img_datas.read(),'image/png')
        email.send()
        return HttpResponse('邮件发送成功,收不到就去垃圾箱找找吧!')
    

     邮件收到效果如下

     这里虽然能添加附件了,但是如果正文想传html的正文内容,这个类里面没有封装对应方法,在EmailMultiAlternatives类里面有个attach_alternative方法可以实现该功能,接着往下看。

    EmailMultiAlternatives

    attach_alternative方法封装在EmailMultiAlternatives类里面,EmailMultiAlternatives类继承了EmailMessage类

    class EmailMultiAlternatives(EmailMessage):
        """
        继承EmailMessage 可以轻松发送multipart / alternative消息。 例如,包括文本的HTML和HTML版本变得更容易
        """
        alternative_subtype = 'alternative'
    
        def __init__(self, subject='', body='', from_email=None, to=None, bcc=None,
                     connection=None, attachments=None, headers=None, alternatives=None,
                     cc=None, reply_to=None):
            """
            Initialize a single email message (which can be sent to multiple
            recipients).
            """
            super().__init__(
                subject, body, from_email, to, bcc, connection, attachments,
                headers, cc, reply_to,
            )
            self.alternatives = alternatives or []
    
        def attach_alternative(self, content, mimetype):
            """Attach an alternative content representation."""
            assert content is not None
            assert mimetype is not None
            self.alternatives.append((content, mimetype))
    

     使用方法 

    #coding:utf-8
    
    from django.http import HttpResponse
    from django.core.mail import send_mail
    from django.core.mail import send_mass_mail
    from django.core.mail import EmailMessage
    from django.core.mail import EmailMultiAlternatives
    import os
    
    
    def file_mail(request):
        '''发送附件'''
        email = EmailMultiAlternatives(
            'Hello',
            'Body goes here',
            '3733505@qq.com',   # 发件人
            ['15721040@163.com'],   # 收件人
            ['373505@qq.com'],                      # cc抄送
            reply_to=['157721040@163.com'],  # “回复”标题中使用的收件人地址列表或元组
            headers={'Message-ID': 'foo'},
        )
        cur = os.path.dirname(os.path.realpath(__file__))
        # templates目录下有个a.png的图片
        filepath = os.path.join(cur, "templates", "ab.png")
        #方法1 attach_file
        email.attach_file(filepath, mimetype=None)
    
        #方法2 attach
        filepath1=os.path.join(cur,"templates","c.png")
        img_datas=open(filepath1,"rb")
        email.attach('c.png',img_datas.read(),'image/png')
    
        #添加html正文
        h='''
        <!DOCTYPE HTML>
        <html>
        <head>
            <meta charset="UTF-8">
            <title>带图片的邮件</title>
        </head>
        <body>
        <a href="https://i.cnblogs.com/posts?cateId=1633461" target="_blank">
            <p>点图片进入jango文章列表<br>
            <img src="https://mail.qq.com/cgi-bin/getqqicon?sid=y4qfcTC8aEOSW00S&uin=-2239048779&mode=newaddr&mailaddr=371933505%40qq.com" height="160" width="270" />
            </p></a>
        <p>
        其它图片:<br>
        <img src="http://www.w3school.com.cn/i/eg_chinarose.jpg" height=150 width=300/></p>
        <p>请注意,插入动画图像的语法与插入普通图像的语法没有区别。</p>
        </body>
        </html>
        '''
        email.attach_alternative(content=h,mimetype='text/html')
    
        email.send()
        return HttpResponse('邮件发送成功,收不到就去垃圾箱找找吧!')
    

     到这里邮件发送相关的功能都实现了

     总的来说,一般推荐用EmailMultiAlternatives类,它继承了EmailMessage

      

  • 相关阅读:
    jQuery实现DropDownList(MVC)
    解决MVC应用程序数据重复加载问题
    MVC应用程序使用jQuery接收Url的参数
    openstack上创建vm实例后,状态为ERROR问题解决
    分布式监控系统Zabbix--完整安装记录-批量添加主机和自动发现端口
    LInux下设置账号有效时间 以及 修改用户名(同时修改用户组名和家目录)
    Rsync+Inotify实时同步环境部署记录
    Shell+Curl监控网站页面访问状态,利用SendEmail发邮件通知
    Shell脚本字符串匹配及日常命令工具
    分布式监控系统Zabbix-3.0.3-完整安装记录(6)-微信报警部署
  • 原文地址:https://www.cnblogs.com/canglongdao/p/14115087.html
Copyright © 2011-2022 走看看