An example of Django sending a message with pictures and attachments in Python

Source: Internet
Author: User
Tags mime file
This article mainly introduces the python send with pictures and attachments of the message, very practical value, the need for friends can refer to.

The group's SRC system needs to be done recently. No security research and development, so can only find me a part-time development of this dish. The system uses the Django framework, and there are many peculiar requirements throughout the process. In a demand, you need to send rich text message to the manufacturer, the vulnerability details, this toss a bit, feel a little harvest, so write an essay.

First I searched the internet for some information, found that Python is sent via smtplib, using MIME format to generate Rich Text messages: Portal

I think, using the Django Framework, the framework with the Mail module, there is no need to introduce Smtplib bar. I just thought, like the portal above, generate a MIME file and then pass

From django.core import Mail Mail.send_mail

In this way, it would be nice to send the file generated by the Mimemultipart object using the As_string () method as a message. Well, it's interesting to try. I sent out a bunch of strings.

Well, failed, do you really want to introduce smtplib?

Despair, this time I saw a sentence: Emailmessage is the Django encapsulated SMTP. Oh? What's the matter? Well, try to look at the source code? Jump to message.py

Class Emailmessage (object): "" "  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): "" "    Initialize a single email message (which can is sent to multiple    re cipients).    All strings used to create the message can be Unicode strings    (or UTF-8 bytestrings). The Safemimetext class would handle any    necessary encoding conversions. ""    

Well! Generally know the usage.

msg = mail. Emailmessage (' Rich Text Mail test ', HTML, From_mail, recipient_list)

That's it. And look at the message.py file.

If to:       if Isinstance (to, six.string_types):        raise TypeError (' to ' argument must is a list or tuple ')      self.to = List (to)

See raise information, understand, we passed to his recipient_list should be a tuple or list

Self.from_email = From_email or settings. Default_from_email

What we passed to him is the mailbox configured in the Django settings.py file, which is in the following format:

# email config# This is the configuration of the settings file in our engineering directory email_backend = ' django.core.mail.backends.smtp.EmailBackend ' email_host_ PASSWORD = ' xxxxxxxx ' email_host_user = ' xxxx@xxxx.xxxx ' email_host = ' smtp.xxxx.com ' Email_port = PORT

OK, so far, we know how to use this class. Let's look at the code in the portal and pick the more important

Msgroot = Mimemultipart (' related ') msgroot[' Subject '] = subjectmsgroot[' from ' = strfrommsgroot[' to '] = Strtomsgtext = Mimetext (plaintext, ' plain ', ' utf-8 ') Msgalternative.attach (msgtext) #设定HTML信息msgText = Mimetext (htmltext, ' html ', ' Utf-8 ') Msgalternative.attach (Msgtext)

Then we compare the code inside the message.py:

Def message (self):    encoding = self.encoding or settings. Default_charset    msg = Safemimetext (Self.body, Self.content_subtype, encoding)    msg = Self._create_message (msg )    msg[' Subject ' = Self.subject    msg[' from '] = Self.extra_headers.get (' from ', self.from_email)    msg[' to '] = Self.extra_headers.get (' To ', ', '. Join (Map (Force_text, self.to)))

The space limit does not paste too much, has the interest to be able to study by oneself. We find that they are not very similar, in fact, after reading the whole message.py we will find something. Originally emailmessage the object of this class, can be regarded as Mimemultipart object plus smtplib send function. And it also has the Attach method, can be like Mimemultipart object splicing Rich Text mail content, good, this has the method! We send rich Text messages via Emailmessage!

#-*-Coding:utf-8-*-# ===============================================================================# @ Creator: Chief pupil # @ date:2017-03-28# construct Rich Text message content # ===================================================================== ==========import osfrom email.mime.image Import mimeimagefrom django.conf import settingsfrom django.core import maildef Add_img (SRC, img_id): "" "Add Picture in Rich Text mail template:p Aram src::p Aram img_id:: Return:" "" fp = open (src, ' rb ') Msg_image = M Imeimage (Fp.read ()) Fp.close () msg_image.add_header (' Content-id ', ' < ' +img_id+ ' > ') return msg_imagedef Send_ Util (): Path = OS.GETCWD () Path_use = path.replace (' \ \ ', '/') HTML = ' <!   DOCTYPE html> 

We set the view function in the views and call the above test methods to try it out:

From django.shortcuts import renderfrom html_to_mail import send_utildef send_mail (Request):  if Send_util ():    return render (Request, ' ok.html ')  else:    return render (Request, ' error.html ')

Randomly configure a map in URLs to point to this view function, and run the Django project directly in the browser get this mapping. Found Mail sent successfully!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.