Python email sending implementation code

Source: Internet
Author: User
Tags imap all mail

SMTP (Simple Mail Transfer Protocol)
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.

The smtplib module also provides SMTP_SSL and LMTP classes, which are basically the same as 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 indicate the SMTP host and port respectively. Note: You can also specify the port number (for example, smtp.163.com: 25) in the host parameter so that the port parameter is unnecessary.

SMTP. login (user, password)

Log on to the SMTP server. Currently, almost all SMTP servers must verify that the user information is valid before sending emails.

SMTP. sendmail (from_addr, to_addrs, msg [, mail_options, rcpt_options])


Example

The code is as follows: Copy code

#! /Usr/bin/env python
#-*-Coding: gbk -*-
# Import smtplib and MIMEText
Import smtplib
From email. mime. text import MIMEText
#############
# To whom, send it to two people here
Mailto_list = ["aaa@juyimeng.com", "bbb@juyimeng.com"]
#####################
# Set the server, user name, password, and mailbox suffix
Mail_host = "smtp.126.com"
Mail_user = "xxx"
Mail_pass = "yyy"
Mail_postfix = "126.com"
######################
Def send_mail (to_list, sub, content ):
'''
To_list: to whom
Sub: Topic
Content: content
Send_mail ("aaa@126.com", "sub", "content ")
'''
Me = mail_user + "<" + mail_user + "@" + mail_postfix + ">"
Msg = MIMEText (content)
Msg ['subobject'] = sub
Msg ['from'] = me
Msg ['to'] = ";". join (to_list)
Try:
S = smtplib. SMTP ()
S. connect (mail_host)
S. login (mail_user, mail_pass)
S. sendmail (me, to_list, msg. as_string ())
S. close ()
Return True
Except t Exception, e:
Print str (e)
Return False
If _ name _ = '_ main __':
If send_mail (mailto_list, "subject", "content "):
Print "sent successfully"
Else:
Print "failed to send"

 

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.

The code is as follows: Copy code

#! /Usr/bin/env python3
# Coding: UTF-8
Import smtplib
From email. mime. multipart import MIMEMultipart
From email. mime. text import MIMEText
From email. mime. image import MIMEImage

Sender = '***'
Else er = '***'
Subject = 'Python email test'
Smtpserver = 'smtp .163.com'
Username = '***'
Password = '***'

# Create message container-the correct MIME type is multipart/alternative.
Msg = MIMEMultipart ('alternative ')
Msg ['subobject'] = "Link"

# Create the body of the message (a plain-text and an HTML version ).
Text = "Hi! NHow are you? NHere is the link you wanted: nhttp: // www.python.org"
Html = """
<Html>
<Head> <Body>
<P> Hi! <Br>
How are you? <Br>
Here is the <a href = "http://www.python.org"> link </a> you wanted.
</P>
</Body>
</Html>
"""

# Record the MIME types of both parts-text/plain and text/html.
Part1 = MIMEText (text, 'plain ')
Part2 = MIMEText (html, 'html ')

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# The HTML message, is best and preferred.
Msg. attach (part1)
Msg. attach (part2)
# Construct an attachment
Att = MIMEText (open ('H: \ python \ 1.jpg ', 'RB'). read (), 'base64', 'utf-8 ')
Att ["Content-Type"] = 'application/octet-stream'
Att ["Content-Disposition"] = 'attachment; filename = "1.jpg "'
Msg. attach (att)
  
Smtp = smtplib. SMTP ()
Smtp. connect ('smtp .163.com ')
Smtp. login (username, password)
Smtp. sendmail (sender, explorer, msg. as_string ())
Smtp. quit ()

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.