Use python to send and receive email example code

高洛峰
Release: 2017-03-21 13:44:49
Original
1636 people have browsed it

About email

Before college, I basically didn’t use email, so I basically didn’t feel its existence and didn’t know its use; however, after college, as I got to know more and more people, my knowledge increased. It is becoming more and more widespread, and email has become a very important communication tool. Some university coursework requires an email to be sent to teachers, registering for a website requires an email, and looking for a job also requires an email. So what is the principle of an email?

Sending mail

SMTP protocol

SMTP (Simple Mail Transfer Protocol) is a simple mail transfer protocol. It is a set of protocols used to transfer mail from the source address to the destination address. Rules that govern how letters are relayed. The SMTP protocol belongs to the TCP/IP protocol suite, which helps each computer find the next destination when sending or relaying letters. Through the server specified by the SMTP protocol, you can send the E-mail to the recipient's server in just a few minutes.

SMTP module in python

Basic steps for using SMTP

  1. Connecting to the server

  2. Log in

  3. Send service request

  4. Log out

import smtplib
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr



def send_email(from_addr, to_addr, subject, password):
    msg = MIMEText("邮件正文",'html','utf-8')
    msg['From'] = u'<%s>' % from_addr
    msg['To'] = u'<%s>' % to_addr
    msg['Subject'] = subject

    smtp = smtplib.SMTP_SSL('smtp.163.com', 465)
    smtp.set_debuglevel(1)
    smtp.ehlo("smtp.163.com")
    smtp.login(from_addr, password)
    smtp.sendmail(from_addr, [to_addr], msg.as_string())


if name == "main":
    # 这里的密码是开启smtp服务时输入的客户端登录授权码,并不是邮箱密码
    # 现在很多邮箱都需要先开启smtp才能这样发送邮件
    send_email(u"from_addr",u"to_addr",u"主题",u"password")
Copy after login

The above demonstrates using smtplib to send emails, and uses SSL encryption, which is relatively safe. Email is used to construct the content of the email. What is sent here is plain text content. I think the most important thing to pay attention to is the password of the email here. . In addition, each company's mail server and port may be different. You can check it before using it.

Here are some commonly used ones:

##163smtp .163.com465 or 99425qqsmtp.11.com 465 or 58725
Email SMTP server SSL protocol port Non-SSL protocol port
Receive mail

POP3 and IMAP

POP refers to the post office protocol, which aims to allow users to access mail in the mailbox server, allowing users to store mail from the server to the local host (i.e. their own computer), and at the same time delete mail stored on the mail server. Mail, and the POP3 server is a receiving mail server that follows the POP3 protocol and is used to receive emails.

Later, the IMAP protocol (Interactive Mail Access Protocol) appeared, which is the interactive mail access protocol. The difference from POP3 is that after IMAP is turned on, the mails received by the email client are still retained on the server. , and at the same time, operations on the client will be fed back to the server, such as deleting emails, marking them as read, etc., and the emails on the server will also take corresponding actions.

Using POP3

Python’s poplib module supports POP3, basic steps:

  1. Connect to the server

  2. Login

  3. Issue a service request

  4. Exit

Common methods of poplib:

MethodDescription##POP3(server)Objectuser(username)pass_(password)stat() status of the mailboxlist([msgnum])retr(msgnum)##dele(msgnum )Mark the specified message for deletionquit()Log out, save changes, unlock the mailbox, end the connection, exitExample
from poplib import POP3

p = POP3('pop.163.com')
p.user('xxxxxxx@163.com')
p.pass_('xxxxxxxx')

p.stat()
...

p.quit()
Copy after login
Instantiation POP3, server is the pop server address
Send the username to the server and wait for the server to return information
Password
Returns the , returns 2-tuple (number of messages, total bytes of message)
Extension of stat(), returns a 3-tuple ( Return information, message list, message size), if msgnum is specified, only the data of the specified message will be returned
Get detailed msgnum, set to Read, returns a 3-tuple (return information, all contents of the message msgnum, the number of bytes of the message). If msgnum is specified, only the data of the specified message will be returned.
Using IMAP

The imaplib package in python supports IMAP4

Common methods:

MethodDescriptionIMAP4(server)Establish a connection with the IMAP server login(user, pass)User password loginlist()View all Folder (IMAP can support creating folders)select()The default folder selection is "INBOX"search()Three parameters, the first is CHARSET, usually None (ASCII), I don’t know what the second parameter is for, the official has not explained itExample
import getpass, imaplib

M = imaplib.IMAP4()
M.login(getpass.getuser(), getpass.getpass())
M.select()
typ, data = M.search(None, 'ALL')
for num in data[0].split():
    typ, data = M.fetch(num, '(RFC822)')
    print 'Message %s\n%s\n' % (num, data[0][1])
M.close()
M.logout()
Copy after login

The above is the detailed content of Use python to send and receive email example code. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!