search
HomeBackend DevelopmentPython TutorialUse python to send and receive email example code

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'' % from_addr
    msg['To'] = u'' % 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")

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()
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()

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!

Statement
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
How are arrays used in scientific computing with Python?How are arrays used in scientific computing with Python?Apr 25, 2025 am 12:28 AM

ArraysinPython,especiallyviaNumPy,arecrucialinscientificcomputingfortheirefficiencyandversatility.1)Theyareusedfornumericaloperations,dataanalysis,andmachinelearning.2)NumPy'simplementationinCensuresfasteroperationsthanPythonlists.3)Arraysenablequick

How do you handle different Python versions on the same system?How do you handle different Python versions on the same system?Apr 25, 2025 am 12:24 AM

You can manage different Python versions by using pyenv, venv and Anaconda. 1) Use pyenv to manage multiple Python versions: install pyenv, set global and local versions. 2) Use venv to create a virtual environment to isolate project dependencies. 3) Use Anaconda to manage Python versions in your data science project. 4) Keep the system Python for system-level tasks. Through these tools and strategies, you can effectively manage different versions of Python to ensure the smooth running of the project.

What are some advantages of using NumPy arrays over standard Python arrays?What are some advantages of using NumPy arrays over standard Python arrays?Apr 25, 2025 am 12:21 AM

NumPyarrayshaveseveraladvantagesoverstandardPythonarrays:1)TheyaremuchfasterduetoC-basedimplementation,2)Theyaremorememory-efficient,especiallywithlargedatasets,and3)Theyofferoptimized,vectorizedfunctionsformathematicalandstatisticaloperations,making

How does the homogenous nature of arrays affect performance?How does the homogenous nature of arrays affect performance?Apr 25, 2025 am 12:13 AM

The impact of homogeneity of arrays on performance is dual: 1) Homogeneity allows the compiler to optimize memory access and improve performance; 2) but limits type diversity, which may lead to inefficiency. In short, choosing the right data structure is crucial.

What are some best practices for writing executable Python scripts?What are some best practices for writing executable Python scripts?Apr 25, 2025 am 12:11 AM

TocraftexecutablePythonscripts,followthesebestpractices:1)Addashebangline(#!/usr/bin/envpython3)tomakethescriptexecutable.2)Setpermissionswithchmod xyour_script.py.3)Organizewithacleardocstringanduseifname=="__main__":formainfunctionality.4

How do NumPy arrays differ from the arrays created using the array module?How do NumPy arrays differ from the arrays created using the array module?Apr 24, 2025 pm 03:53 PM

NumPyarraysarebetterfornumericaloperationsandmulti-dimensionaldata,whilethearraymoduleissuitableforbasic,memory-efficientarrays.1)NumPyexcelsinperformanceandfunctionalityforlargedatasetsandcomplexoperations.2)Thearraymoduleismorememory-efficientandfa

How does the use of NumPy arrays compare to using the array module arrays in Python?How does the use of NumPy arrays compare to using the array module arrays in Python?Apr 24, 2025 pm 03:49 PM

NumPyarraysarebetterforheavynumericalcomputing,whilethearraymoduleismoresuitableformemory-constrainedprojectswithsimpledatatypes.1)NumPyarraysofferversatilityandperformanceforlargedatasetsandcomplexoperations.2)Thearraymoduleislightweightandmemory-ef

How does the ctypes module relate to arrays in Python?How does the ctypes module relate to arrays in Python?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)