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.
Basic steps for using SMTP
Connecting to the server
Log in
Send service request
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:
##163 | smtp .163.com | 465 or 994 | 25 |
qq | smtp.11.com | 465 or 587 | 25 |
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:
- Connect to the server
- Login
- Issue a service request
- Exit
Common methods of poplib:
##POP3(server)
Instantiation POP3 | Object, server is the pop server address
|
user(username)
Send the username to the server and wait for the server to return information |
|
pass_(password)
Password |
|
stat()
Returns the | status of the mailbox , returns 2-tuple (number of messages, total bytes of message)
|
list([msgnum])
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 |
|
retr(msgnum)
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. |
| ##dele(msgnum )
Mark the specified message for deletion |
| quit()
Log out, save changes, unlock the mailbox, end the connection, exit |
|
Example
from poplib import POP3
p = POP3('pop.163.com')
p.user('xxxxxxx@163.com')
p.pass_('xxxxxxxx')
p.stat()
...
p.quit()
Copy after login
Using IMAP
The imaplib package in python supports IMAP4
Common methods:
MethodIMAP4(server)
Establish a connection with the IMAP server |
| login(user, pass)
User password login |
| list()
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 it |
|
Example
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!