Python implements Smtplib to send mail instances with various attachments, pythonsmtplib

Source: Internet
Author: User

Python implements Smtplib to send mail instances with various attachments, pythonsmtplib

These two days I was interested in the Python mail module, so I checked the information. At the same time, various problems have also been encountered in the actual coding process. Next I will share my story with smtplib.

Prerequisites

In my previous blog post, I explained the necessary conditions for sending emails. This is also applicable. Generally, you need to enable the SMPT/POP service for your mailbox.

Core knowledge points

Because today we mainly explain how to send emails with attachments, the core is the attachment. How can I send attachments?

In fact, it is not difficult to understand the problem. Because the email is sent through the application layer> transport layer> network layer> data link layer> physical layer. All these steps have become bit streams. Therefore, whether it is plain text, images, or other types of files. In the face of BITs, they are all equal. Therefore, we can only send attachments in the plain text mode, with some special tags added.

# First, xlsx-type 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('kennypolic', 'rb '). read () mp3part. add_header ('content-disposition', 'attachment ', filename='benny}') msg. attach (mp3part)

After the three small sections of code, you must have understood it. It is nothing more than packaging with MIMEApplication, and then setting the content. Finally, add it to the email content. This step is done.

Complete code

# Coding: UTF-8 # _ author _ = 'Mark sinoberg '# _ date _ = '2014/2/26' # _ Desc _ = implement import for sending emails with various attachment types urllib, urllib2import smtplibfrom email. mime. multipart import MIMEMultipartfrom email. mime. text import MIMETextfrom email. mime. application import MIMEApplicationusername = '156408xxxxx @ 163.com 'password = 'xxxxxxxx' sender = usernamereceivers = ','. join (['10643xxxx2 @ qq.com ']) # As shown in the name, Multipart is composed of multiple parts. Msg = MIMEMultipart () msg ['subobject'] = 'python mail test' msg ['from'] = sendermsg ['to'] = receivers # below is the text section, that is, plain text puretext = MIMEText ('I am a plain text part,') msg. attach (puretext) # below is the attachment section, which is divided into several types # first, xlsx 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 ('bea' Uty.jpg ', 'rb '). read () jpgpart. add_header ('content-disposition', 'attachment ', filename='beauty.jpg') msg. attach (jpgpart) # mp3 attachment mp3part = mimeapplication(open('kennypolic', 'rb '). read () mp3part. add_header ('content-disposition', 'attachment ', filename='benny}') msg. attach (mp3part) # try: client = smtplib. SMTP () client. connect ('smtp .163.com ') client. login (username, password) client. se Ndmail (sender, receivers, msg. as_string () client. quit () print 'emails with various attachments are successfully sent! 'Small t smtplib. SMTPRecipientsRefused: print 'recipient refused 'counter t smtplib. SMTPAuthenticationError: print 'auth error' handle T smtplib. SMTPSenderRefused: print 'sender refused 'counter t smtplib. SMTPException, e: print e. message

Verification Result

Nothing is more convincing than a picture.

Error Summary

The following error occurs:

D:\Software\Python2\python.exe E:/Code/Python/MyTestSet/mail/withappedix.pyTraceback (most recent call last): File "E:/Code/Python/MyTestSet/mail/withappedix.py", line 51, in <module>  client.sendmail(sender, receivers, msg.as_string()) 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 83, in flatten  self._write(msg) File "D:\Software\Python2\lib\email\generator.py", line 115, in _write  self._write_headers(msg) File "D:\Software\Python2\lib\email\generator.py", 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\Python2\lib\email\header.py", line 370, in _encode_chunks  _max_append(chunks, s, maxlinelen, extra) File "D:\Software\Python2\lib\email\quoprimime.py", line 97, in _max_append  L.append(s.lstrip())AttributeError: 'list' object has no attribute 'lstrip'Process finished with exit code 1

My solution is:

Copy codeThe Code is as follows:
Extends er parameter was list type. either it shocould be list converted to string using join method or if it is a single recipient, then pass it as a string only

Yes, that isreceivers = ','.join(['10XXXXXXXX@qq.com'])。This is done.

Maybe the error you encountered is not mine, so don't worry. I have a complete error code table here. You can compare your error codes to find the specific cause of the error. In this way, the efficiency will be higher.

During the coding process, I also encountered many unexpected errors. These error codes are very useful for us. This is helpful for testing the code and finding the cause of the error.

Error Codes of Enterprise bounce messages

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.