Changeset - 29e10c6a1551
[Not reviewed]
0 1 0
Lance Edgar (lance) - 7 years ago 2018-02-22 13:15:54
lance@edbob.org
Add email attachment MIME type for MS Word .doc files
1 file changed with 1 insertions and 0 deletions:
0 comments (0 inline, 0 general)
rattail/mail.py
Show inline comments
 
@@ -398,96 +398,97 @@ class Email(object):
 
        if template is UNSPECIFIED:
 
            template = self.config.get('rattail.mail', '{}.subject'.format(self.key),
 
                                       default=self.default_subject)
 
            if not template:
 
                template = self.config.get('rattail.mail', 'default.subject')
 
        if template and render:
 
            return Template(template).render(**data)
 
        return template
 

	
 
    def get_complete_subject(self, data={}, render=True, prefix=UNSPECIFIED, template=UNSPECIFIED):
 
        """
 
        Returns the value for the message's ``Subject:`` header, i.e. the base
 
        subject with the prefix applied.  Note that config may provide the
 
        complete subject also, in which case the prefix and base subject are
 
        not considered.
 

	
 
        :rtype: str
 
        """
 
        if prefix is UNSPECIFIED:
 
            prefix = self.get_prefix(data)
 
        prefix = (prefix or "").rstrip()
 
        if prefix:
 
            prefix = "{} ".format(prefix)
 
        return "{}{}".format(prefix, self.get_subject(data, render=render, template=template))
 

	
 
    def get_template(self, type_):
 
        """
 
        Locate and return the Mako email template of the given type
 
        (e.g. 'html'), or ``None`` if no such template can be found.
 
        """
 
        try:
 
            return self.templates.get_template('{0}.{1}.mako'.format(self.key, type_))
 
        except TopLevelLookupException:
 
            if self.fallback_key:
 
                try:
 
                    return self.templates.get_template('{0}.{1}.mako'.format(self.fallback_key, type_))
 
                except TopLevelLookupException:
 
                    pass
 

	
 
    def normalize_attachments(self, attachments):
 
        normalized = []
 
        for attachment in attachments:
 
            if isinstance(attachment, six.string_types):
 
                attachment = self.normalize_attachment(attachment)
 
            normalized.append(attachment)
 
        return normalized
 

	
 
    ATTACHMENT_MIME_MAP = {
 
        '.doc': 'application/msword',
 
        '.pdf': 'pdf',
 
        '.xls': 'vnd.ms-excel',
 
    }
 

	
 
    def normalize_attachment(self, path):
 
        root, ext = os.path.splitext(path)
 
        ext = ext.lower()
 
        if ext == '.csv':
 
            with open(path, 'rb') as f:
 
                part = MIMEText(f.read(), 'csv', 'utf_8')
 
            filename = os.path.basename(path)
 
            part.add_header('Content-Disposition', 'attachment; filename="{}"'.format(filename))
 
            return part
 
        else:
 
            mimetype = self.ATTACHMENT_MIME_MAP.get(ext)
 
            if mimetype:
 
                with open(path, 'rb') as f:
 
                    part = MIMEApplication(f.read(), mimetype)
 
                filename = os.path.basename(path)
 
                part.add_header('Content-Disposition', 'attachment; filename="{}"'.format(filename))
 
                return part
 
        raise ValueError("Magic is not (yet) supported, please construct your own attachments for file: {}".format(path))
 

	
 
    def make_message(self, data={}, attachments=[], inlines=[],
 
                     subject_prefix=UNSPECIFIED, subject_template=UNSPECIFIED,
 
                     sender=UNSPECIFIED, replyto=UNSPECIFIED,
 
                     to=UNSPECIFIED, cc=UNSPECIFIED, bcc=UNSPECIFIED):
 
        """
 
        Returns a proper email ``Message`` instance which may be sent via SMTP.
 
        """
 
        txt_template = self.get_template('txt')
 
        html_template = self.get_template('html')
 
        attachments = self.normalize_attachments(attachments)
 

	
 
        # TODO: provide more defaults?
 
        data.setdefault('six', six)
 

	
 
        if txt_template and html_template:
 

	
 
            txt_part = MIMEText(txt_template.render(**data), _charset='utf_8')
 

	
 
            html_part = MIMEText(html_template.render(**data), _subtype='html', _charset='utf_8')
 
            if inlines:
 
                html_part = MIMEMultipart(_subtype='related', _subparts=[html_part] + inlines)
 

	
 
            msg = MIMEMultipart(_subtype='alternative', _subparts=[txt_part, html_part])
 
            if attachments:
 
                msg = MIMEMultipart(_subtype='mixed', _subparts=[msg] + attachments)
0 comments (0 inline, 0 general)