django之三十二--发送满足【邮件正文值为一个html页面+有多个附件】的单个邮件

一、写这篇博客的目的

主要记录如何通过django来实现这个功能:发送满足【邮件正文值为一个html页面+有多个附件】的单个邮件;

发送满足【邮件正文值为一个html页面+有多个附件】的单个邮件,可以使用类EmailMultiAlternative

EmailMultiAlternative提供了三个方法:attach_file()attach_alternative()send(),这三个方法的主要作用分别是:

  • attach_file()的主要作用:把指定的一个文件当做邮件附件;
  • attach_alternative()的主要作用:使邮件正文为一个指定的html页面;
  • send()的主要作用:执行发送邮件的动作;

完整操作流程可以看接下来的内容;

 

二、完整操作流程

1、第一步:在【settings.py】里新增邮箱配置信息

# 配置qq邮箱信息

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'  # 值必须为这个

EMAIL_USE_SSL = True  # SSL加密方式,值必须为True

EMAIL_HOST = 'smtp.qq.com'  # 发送邮件的qq邮箱的SMTP服务器

EMAIL_PORT = 465  # QQ邮箱对应的SMTP服务器端口

EMAIL_HOST_USER = '[email protected]'  # 发件人

EMAIL_HOST_PASSWORD = 'xolnfbqgdybxji11'  # qq授权码(不能使用qq密码只能使用qq授权码)

EMAIL_FROM = 'Rainbow<[email protected]>'  # 邮件显示的发件人

2、第二步:在【helloworld/hello/views.py】里新增视图函数

3、第三步:在【helloworld/helloworld/urls.py】里新增url匹配规则

url(r"^send_email_004/$",views.send_email_004),

4、第四步:重启服务

5、第五步:任一浏览器上输入url地址【http://0.0.0.0:8000/send_email_004/】进行访问后,查看结果

 

三、相关知识点

1、EmailMultiAlternatives里的方法【__init__】的源码简单分析

class EmailMultiAlternatives(EmailMessage):

    """

    A version of EmailMessage that makes it easy to send multipart/alternative

    messages. For example, including text and HTML versions of the text is

    made easier.

    """

    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 []

方法【__init__】里的几个主要入参的分析:

  • subject: (必填,数据类型为字符串)邮件标题;
  • body: (必填,数据类型为字符串)邮件正文;
  • from_email: (非必填,数据类型为字符串)发件邮箱;
  • to: (非必填,数据类型为列表)列表中每个值都是一个接收邮件的邮箱地址;

2、EmailMultiAlternatives里的方法【attach_file】的源码简单分析 

  def attach_file(self, path, mimetype=None):

        """

        Attach a file from the filesystem.



        Set the mimetype to DEFAULT_ATTACHMENT_MIME_TYPE if it isn't specified

        and cannot be guessed.



        For a text/* mimetype (guessed or specified), decode the file's content

        as UTF-8. If that fails, set the mimetype to

        DEFAULT_ATTACHMENT_MIME_TYPE and don't decode the content.

        """

        path = Path(path)

        with path.open('rb') as file:

            content = file.read()

            self.attach(path.name, content, mimetype)

从方法【attach_file】的源码可以大概看出来,其实方法【attach_file】是对方法【attach】的进一步封装;

3、EmailMultiAlternatives里的方法【attach】的源码简单分析   

 def attach(self, filename=None, content=None, mimetype=None):

        """

        Attach a file with the given filename and content. The filename can

        be omitted and the mimetype is guessed, if not provided.



        If the first parameter is a MIMEBase subclass, insert it directly

        into the resulting message attachments.



        For a text/* mimetype (guessed or specified), when a bytes object is

        specified as content, decode it as UTF-8. If that fails, set the

        mimetype to DEFAULT_ATTACHMENT_MIME_TYPE and don't decode the content.

        """

        if isinstance(filename, MIMEBase):

            assert content is None

            assert mimetype is None

            self.attachments.append(filename)

        else:

            assert content is not None

            mimetype = mimetype or mimetypes.guess_type(filename)[0] or DEFAULT_ATTACHMENT_MIME_TYPE

            basetype, subtype = mimetype.split('/', 1)



            if basetype == 'text':

                if isinstance(content, bytes):

                    try:

                        content = content.decode()

                    except UnicodeDecodeError:

                        # If mimetype suggests the file is text but it's

                        # actually binary, read() raises a UnicodeDecodeError.

                        mimetype = DEFAULT_ATTACHMENT_MIME_TYPE



            self.attachments.append((filename, content, mimetype))

截取这部分源码:

mimetype = mimetype or mimetypes.guess_type(filename)[0] or DEFAULT_ATTACHMENT_MIME_TYPE

basetype, subtype = mimetype.split('/', 1)

从这部分源码可以简单看出来:当入参mimetype值为Nonedjango会自动根据附件文件名来推测MIME内容类型的值并赋值给入参mimetype,然后入参mimetype的新值做后续相关处理;

 

4、每个应用的资源存放位置

什么是资源?比如:一个图片、一个html页面、一个css、一个js、一个视频、一个pdf、一个word、一个txt,等等这些都是不同的资源类型;

每个项目的应用都有对应所属的资源,那么每个应用的资源存放位置要怎么定呢?怎么定的思路,个人做法主要是这个思路步骤:

  • 第一步:每个应用的资源存放位置定为在每个应用根目录下的某个手动新增的文件夹,比如该新增的文件夹名为【public】;      
  • 第二步:在文件夹【public】里按不同的资源类型新增对应不同的文件夹,比如新增的文件夹名为【css】和【word】;
  • 第三步:在文件夹【word】里按不同的数据表/按不同的业务模块新增对应不同的文件夹,比如新增的文件夹名为【user】和【test】;

这样的思路步骤的主要目的是:每个应用的资源在各自应用目录里维护,大大减少项目代码的耦合度,方便后续维护;

以一个应用【hello】为例,应用【hello】的资源存放位置所对应的具体的文件层级结构大概如下:

 

猜你喜欢

转载自blog.csdn.net/LYX_WIN/article/details/114917651
今日推荐