Send email via python (1)

Source: Internet
Author: User
Tags imap all mail

Send email via python (1)

Send email via python (1)

 

Recently, a small application was designed to send an excel file based on the email address in the file, and the recipient received the mail in a webpage format.

The following is a summary of some knowledge points involved in sending emails via python.

I. first introduce the Smtp protocol and POP3 protocol

 

SMTP (Simple Mail Transfer Protocol)

The http://www.rfc-editor.org/info/rfc821 RFC821 documentation details the protocol information;

The Mail Transfer Agent (MTA) program uses the SMTP protocol to send emails to the recipient's Mail server. The SMTP protocol can only be used to send mails and cannot be used to receive mails. Most email sending servers use the SMTP protocol. The default TCP port number of SMTP protocol is 25.

An important feature of the SMTP protocol is its ability to transmit mails through relay. It works in two situations: one is the transmission of email from the client to the server, and the other is the transmission from one server to another.

POP3 (Post Office Protocol) & IMAP (Internet Message Access Protocol)

POP protocol and IMAP Protocol are the two most common protocols used for mail receiving. Almost all mail clients and servers support these two protocols.

The POP3 protocol provides users with a simple and standard way to access their email addresses and obtain emails. The mail client that uses POP3 Protocol Usually works in the process of connecting to the server, getting all information and saving it on the user host, deleting the messages from the server, and then disconnecting. The default TCP port number for POP3 is 110.

The IMAP Protocol also provides a convenient Mail Download service, allowing users to read offline. The email client that uses the IMAP Protocol usually keeps the information on the server until the user explicitly deletes it. This feature allows multiple clients to manage one mailbox at a time. The IMAP Protocol provides the abstract browsing function, allowing users to determine whether to download after reading the arrival time, topic, sender, size, and other information of all emails. The default TCP port number of the IMAP protocol is 143.

 

 

 

Ii. Module Introduction

Sending emails in python involves two modules: smtplib and email.

 

 

1. smtplib Module

 

This module provides the following functions:

Link to smtp Server

Log on to the smtp server

Send email

 

 

Http://www.cnpaf.net/Class/SMTP/200408/106.html

Smtplib. SMTP ([host [, port [, local_hostname [, timeout])

SMTP constructor indicates the connection to the SMTP server. Through this connection, we can send commands to the smtp server to execute relevant operations (such as login and email sending ). This class provides many methods, which will be described below. All its parameters are optional. The host parameter indicates the smtp server host name. In the above example, the smtp host is smtp.yeah.net; port indicates the smtp service port. The default value is 25; if the two parameters are provided when an SMTP object is created, the connect method is automatically called during initialization to connect to the server.
The smtplib module also provides SMTP_SSL and LMTP classes, which are basically the same as SMTP.
Methods provided by smtplib. SMTP:

SMTP. set_debuglevel (level)

Set whether to use the debugging mode. The default value is False, that is, non-debug mode, indicating that no debugging information is output.

SMTP. connect ([host [, port])

Connect to the specified smtp server. The parameters represent the smpt host and port respectively. Note: You can also specify the port number (for example, smpt.yeah.net: 25) in the host parameter so that the port parameter is unnecessary.

SMTP.doc md (cmd [, argstring])

Send commands to the smtp server. The optional parameter argstring indicates the command parameter.

 

 

 

2. email Module

This module designs the mail format

And how to set and send various complex emails (attachments, images, audios, and other webpage formats)

 

 

 

3. Code Implementation

 

 

# Encoding: utf-8import sysimport osimport timeimport xlrdimport smtplibfrom email. mime. text import MIMETextfrom email. utils import COMMASPACE, formatdatefrom email import encodersreload (sys) sys. setdefaultencoding ('utf8') def readFileFormal (fileName): data = xlrd. open_workbook (fileName) # Read the excel file table = data. sheet_by_name (u 'sheet1') # You can obtain a worksheet using rownum = table. nrows colnum = table. ncols flag = Fa Lse # obtain the table title = table. cell (0, 0). value if colnum! = 16: flag = True return flag # convert execl data into html format def produceHtml (baseinfo, deductinfo, rowdata): content = '''
Name Student ID Score  
'''Return content # send the email def send_mail (mail_host, mail_user, mail_password, receiveAdd, subject, content): # receiveAdd: recipient; subject: topic; content: mail content flag = False info = ''sender = mail_user + <+ mail_user +> # Here, hello can be set at will. After receiving the mail, the message msg = MIMEText (content, _ subtype = 'html', _ charset = 'utf-8') # create an instance, set msg ['subobject'] = Subject # Set topic msg ['from'] = sender msg ['to'] = receiveAdd try: s = smtplib. SMTP () S. connect (mail_host) # connect to the smtp server s. login (mail_user, mail_password) # log on to the server s. sendmail (sender, receiveAdd, msg. as_string () # Send email s. close () flag = True then t Exception, e: # print str (e) info = str (e) flag = False return flag, info def start (mailhost, mailuser, mailpassword, filename): baseinfo, deductinfo, alldata, title = readFile (filename) stateinfo = [] for I in range (len (alldata): rowdata = alldata [I] c Ontent = produceHtml (baseinfo, deductinfo, rowdata) # Can baseinfo and defuctinfo be fixed to death? Receiveadd = rowdata [len (rowdata)-1] # print receiveadd if receiveadd! = '': Flag, info = send_mail (mailhost, mailuser, mailpassword, receiveadd, title, content) if flag: # print receiveadd ++ successfully sent + + time. ctime (time. time () sendinfo = receiveadd ++ successfully sent + + time. ctime (time. time () else: # print failed to send sendinfo = 'failed to send 'else: # print ('This contact address does not exist !! ') Sendinfo =' This contact address does not exist !! 'Stateinfo. append (sendinfo) producetxt (stateinfo) # The log file is generated to record the time and information for sending the email def producetxt (info): timeinfo = time. strftime ('% Y-% m-% d (% X)', time. localtime (time. time () filename = OS. getcwd () filename = filename + '/' + timeinfo + '.txt 'filename = 'logfile'{'.txt' f = open (filename, 'A') for I in range (len (info )): f. write (info [I] + '') f. close () def issendmail (mail_host, mail_user, mail_password): # receiveAdd: recipient; subject: subject; content: Mail content flag = False info = ''try: s = smtplib. SMTP () s. connect (mail_host) # connect to the smtp server s. login (mail_user, mail_password) # log on to the server s. close () flag = True then t Exception, e: # print str (e) info = str (e) flag = False return flag, info # Check whether the sender's email can be logged on to the server and whether the verification is successful
Def isExisting (user, password): flag = False # ostrich = smtp.163.com # Set server # user = iphonexb@163.com # username # password = iphonexiaoxiao55 # password host = user. strip ('') hostlist = host. split ('@') host = hostlist [1] host = 'smtp. '+ host # print host flag, info = issendmail (host, user, password) # print flag, info return flag # def initValue (user, password, filenameStr): host = user. strip ('') hostlist = host. split ('@') host = hostlist [1] host = 'smtp. '+ host mailhost = host # Set server mailuser = user # username mailpassword = password # password filename = filenameStr start (mailhost, mailuser, mailpassword, filename) '''if _ name _ = _ main __: print # isExisting () mail_host = smtp.163.com # Set the server mail_user = xxx@163.com # username mail_password = xxxxx # password mail_postfix = 163.com # The suffix filename = 'hangzhou.xls 'start (mail_host, mail_user, mail_password, filename )'''

Interface 1 and 2

 



Verification Error

 

 

 

 

3. Various Errors may occur during program implementation:

 

Http://blog.csdn.net/mindmb/article/details/7898528

Solve UnicodeDecodeError: 'ascii 'codec can't decode byte 0xe5 in position 108: ordinal not in range (128

Http://www.oschina.net/code/snippet_111708_15987

 

If authentication fails, the password and account are incorrect when you log on to the server.

(535, 'authentication failed 95187d9c-ee91-45a9-b7d5-c495c23abbd7 ')

 

4 Authentication failed, please open smtp flag first!

Http://blog.csdn.net/bruce128/article/details/8761949

(535, 'error: authentication failed ')

Http://bbs.chinaunix.net/thread-717982-1-1.html

 

(454, 'error: authentication failed, system busy ')

In general, to ensure the security of your mailbox, the POP3/SMTP switch is set for QQ mailbox. The default setting is "off". Enable the POP3/SMTP function when you need it ". After POP3/SMTP is disabled, you can only accept emails, but cannot send emails.

 

If it is not because of the Setting problem, try QQ to change the logon password again. At this time, the mailbox password needs to be reset.

 

If it is useless after resetting, you can try it in a few days. It is possible that the QQ Mail Server considers your email as spam. There is no final answer to the online search, but this is also common in QQ mail.

 

Also, try another mail client, KOOMAIL.

The smtp server with 163.com is relatively stable and has unknown problems with qq.

 

 

The above error message is related to smtp server authentication.

 

 


 

 

 



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.