Python Module Quest smtplib send messages with a variety of attachments __python

Source: Internet
Author: User
Tags comparison table generator how to send mail in python

These two days are more interested in Python's mail modules, so they check the data. At the same time in the actual coding process also encountered a variety of problems. Now I'm going to share my story with Smtplib. Prerequisite Conditions

In my last blog post, I explained the necessary conditions for sending mail. The same is true here. Basically is to open the mailbox Smpt/pop service and so on. If you don't understand, you can look at sending plain text messages. It's a good story. :-) Core Knowledge points

Because today's main explanation is how to send mail with attachments, then the core must be attached. How can we send attachments?

In fact, we change the way of thinking, it is not difficult to understand. Because we send mail, through the application Layer –>> Transport Layer –>> Network layer –>> Data Link layer –>> physical layer. This sequence of steps has all become a bit stream. So whether it's plain text, pictures, or other types of files. In front of the bit stream, all are equal. So we send the attachment, but also in accordance with the mode of sending plain text to do on the line, but add some special tags can be.

\# First is the xlsx type of attachment
Xlsxpart = mimeapplication (open (' test.xlsx ', ' RB '). Read ())
Xlsxpart.add_header (' Content-disposition ', ' attachment ', filename= ' test.xlsx ')
Msg.attach (xlsxpart) \#

jpg type attachment
Jpgpart = Mimeapplication (Open (' beauty.jpg ', ' RB '). Read ())
jpgpart.add_header (' content-disposition ', ' attachment ', Filename= ' beauty.jpg ')
Msg.attach (Jpgpart) \# mp3

type attachment
Mp3part = mimeapplication (open (' Kenny.mp3 ', ' RB '). Read ())
mp3part.add_header (' content-disposition ', ' attachment ', filename= ' Benny.mp3 ')
Msg.attach ( Mp3part)

After these three pieces of code, you must have been very clear. The only thing is to use mimeapplication for packaging, and then set the content. Finally, add to the content of the message. It's just a few steps and it's done. The complete code

# coding:utf-8 # __author__ = ' Mark Sinoberg ' # __date__ = ' 2016/5/26 ' # __desc__ = implementation sends mail import with various attachment types Urll IB, Urllib2 import smtplib from Email.mime.multipart import mimemultipart from email.mime.text import mimetext from email. Mime.application Import mimeapplication username = ' 156408XXXXX@163.com ' password = ' XXXXXXXX ' sender = Username Receiver s = ', '. Join ([' 10643XXXX2@qq.com ']) # as shown in name: multipart is multiple parts msg = Mimemultipart () msg[' Subject '] = ' Python mail Test ' ms  G[' from '] = Sender msg[' to '] = receivers # Below is the text part, that is, the plain text puretext = Mimetext (' I am a plain text section, ') Msg.attach (puretext) # Below is the attachment section , which is divided into several types # The first is the xlsx type of attachment Xlsxpart = mimeapplication (open (' test.xlsx ', ' RB '). Read ()) Xlsxpart.add_header (' Content-disposition ', ' attachment ', filename= ' test.xlsx ') Msg.attach (xlsxpart) # jpg type attachment Jpgpart = Mimeapplication (
Open (' beauty.jpg ', ' RB '). Read ()) Jpgpart.add_header (' content-disposition ', ' attachment ', filename= ' beauty.jpg ') Msg.attach (Jpgpart) # MP3 type attachment Mp3part = Mimeapplication (Open (' Kenny.mp3 ', ' RB '). Read ()) Mp3part.add_header (' content-disposition ', ' attachment ', filename= ' Benny.mp3 ') Msg.attach (Mp3part) # # below begins to really send mail try:client = smtplib. SMTP () client.connect (' smtp.163.com ') client.login (username, password) client.sendmail (sender, Receivers, MSG. As_string ()) client.quit () print ' message with various attachments was sent successfully. ' Except Smtplib. Smtprecipientsrefused:print ' recipient refused ' except Smtplib. Smtpauthenticationerror:print ' Auth error ' except Smtplib. Smtpsenderrefused:print ' Sender refused ' except Smtplib.
 Smtpexception,e:print E.message
Validation Results

Nothing is more convincing than a picture. As shown in figure
Error Summary

The error I encountered is as follows:

D:\Software\Python2\python.exe e:/code/python/mytestset/mail/withappedix.py Traceback (most recent call last): File "E" :/code/python/mytestset/mail/withappedix.py ", Line Wuyi, in <module> client.sendmail (sender, receivers, Msg.as_st
  Ring ()) File "D:\Software\Python2\lib\email\message.py", line 137, in As_string g.flatten (self, unixfrom=unixfrom) File "D:\Software\Python2\lib\email\generator.py", line, in Flatten Self._write (msg) File D:\Software\Python2\l ib\email\generator.py ", line up, in _write self._write_headers (msg) File" D:\SOFTWARE\PYTHON2\LIB\EMAIL\GENERATOR.P Y ", line 164, in _write_headers V, Maxlinelen=self._maxheaderlen, header_name=h). Encode () File" D:\Software\Python2\ lib\email\header.py ", line 410, in encode value = Self._encode_chunks (Newchunks, Maxlinelen) File" D:\Software\Pytho n2\lib\email\header.py ", line 370, in _encode_chunks _max_append (chunks, S, Maxlinelen, extra) File" D:\Software\Pyt Hon2\lib\email\quoprimime.pY ", line, in _max_append l.append (S.lstrip ()) Attributeerror: ' List ' object has no attribute ' Lstrip ' Process fini
 Shed with exit code 1

My solution is.
Receiver parameter was list type. Either it should be list converted to string by using join method or if it's a single recipient, then pass it as a string on Ly

Yes, that's receivers = ', '. Join ([' 10XXXXXXXX@qq.com ']). It's done.

Perhaps, you encountered the mistake is not my this, then also need not worry, I have here a relatively complete error code comparison table. You can look up the exact cause of the error by comparing your error code. In this way, the efficiency will be a little higher.

In the process of coding, I also encountered a lot of unexpected mistakes. And these error codes are very useful for us. This is helpful for us to test the code and find out why it went wrong.

The error code Comparison of Enterprise retreat letter
(^__^) Xi hee ..... The font is big enough.

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.