


Teach you step by step how to use Python to easily send emails
#Preface
Nowadays, the pace of life is accelerating, and the communication methods between people are also very different. In order to make communication more convenient, email was born. As we all know, email is actually the client and server. The same as sending and receiving data, it has a function of sending and receiving messages. The communication protocols of email are SMTP, POP3, and IMAP, and they all belong to the tcp/ip protocol, such as the QQ mailbox and NetEase mailbox that we often use. These are the same patterns.
Preparation
Editor: sublime text 3
Module: smtplib and email
Project Implementation
1. Installation
pip install smtplib pip install email
Note: There is a small pit here. You cannot install smtplib directly as above, otherwise it will not be installed. You have to install PyEmail first, because your smtplib is integrated into this module, just like the pillow module is integrated into PIL. Another normal installation is Can.
2. Open the pop3 SMTP imap service and learn the email authorization code
Any email If you want to send emails, you must first activate the above services so that emails can be communicated, and you must also have an email authorization code, such as QQ email:
Open QQ email and select Settings --------Account, and then start the service.
After starting the service, click to generate the authorization code and save the authorization code. To obtain the authorization code, you only need to send a text message or dynamic token with your registered mobile phone number.
3. Build a mail port and establish a connection
import smtplib sm=smtp.SMTP() # 初始化连接 sm.connect('邮件服务器地址','端口') #建立连接 sm.login('邮箱账号','邮箱密码/授权码') #登陆账户 sm.sendmail('邮件发送方','邮件接受方','邮件内容') #发送邮件 sm.quit() #关闭连接,结束邮件服务
Got it After the above knowledge, let’s try to log in. I’ll take QQ mailbox as an example:
有这样的标识表示登陆成功,顺便强调一句,在这里我为什么没有配置邮件服务器端口,因为服务器已经帮我们配置好了,默认的都是25号端口,如果你担心邮件的安全问题,比如会被黑客截胡,你也可以使用ssl链接传输:
同样它的端口也是默认配置好了,他的端口号为465,为了安全,咱们选择这项。
4.构建邮件内容部分
这里我们需要用到email模块,我们都知道,邮件一般可以发很多东西,比如说文本,图片,文件等等,那么我们来看看吧。
一、文本
导入模块
from email.mime.text import MIMEText
填充文本
在此之前我们得知道它的具体用法:
MIMEText(‘邮件内容’,‘类型’, '编码')
邮件内容为字符串
类型: text/plain text/html
编码 : utf-8 gbk
构造文本
MIMEText('hello','text/plain','utf-8')
构造超文本
MIMEText('<a href='www.baidu.com'>点击此处有惊喜</a>','text/html','utf-8')
下面我们来实际操作下吧。
非常成功收到了邮件了。正是2091500484这个邮箱给我发的。当然我们这样只是实现了最简单的功能,
我们需要将它格式规范下,比如给它添加个开头结尾什么的。我们需要导入构建邮件完整内容的模块:
from email.header import Header
然后设置头部,内容,尾部
msg1['From']=Header('你是猪吗') #设置发件人昵称msg1['To']=Header('hwhrr123321@163.com') #设置收件人昵称msg1['Subject'] = Header('我是猪') #设置标题
可以看到,是不是觉得很有趣了,快来试试吧,哈哈哈。。。
二、图片
发了文本后我们还想发一张图片,那该怎么办呢?莫慌,此时需要先导入发图片的模块:
from email.mime.image import MIMEImage
然后我们在读取图片文件将它添加到邮件中去。
ff=open('1.jpg','rb').read() #打开文件fd=MIMEImage(ff,'subtype') #初始化fd.add_header('Content-ID','1.jpg') #添加到头部
可以看到图片并没有显示出来,那么这是怎么回事,哦,原来图片是依托附件而存在的,要么是html要么是附件,但是两者都需要附件模块的支持,下面我们导入附件模块:
from email.mime.multipart import MIMEMultipart
1.将图片插入到html中
也就是将图片插入到正文部分,而非附件的形式。
msg3 = MIMEMultipart('related')msg3['From'] = '你是猪吗'msg3['To'] = 'hwhrr123321@163.com'msg3['Subject'] = '我是猪'msg4 = MIMEMultipart('alternative') #构建一个附件msg3.attach(msg4) #将附件引入到另一个附件text=""" <html> <body> <img src='cid:img' tittle='I am pig'> </body> </html>"""msg4.attach(MIMEText(text, 'html', 'utf-8')) #将html插入到附件中ff=open('2.jpg','rb')img = MIMEImage(ff.read()) #将图片读取到附件中ff.close()img.add_header('Content-ID','<img>') #添加图片头部msg3.attach(img) #将图片添加到附件sm.sendmail('2091500484@qq.com','hwhrr123321@163.com',msg3.as_string()) #发送sm.quit()
可以看出,过程还是比较复杂的,比单纯附件添加图片麻烦点,主要是嵌套了一层附件结构。
2.将图片引入到附件中
这个比较好实现。如图:
三、文件
在发送文件前,我们要考虑的一个问题是,我们读取它要以二进制的形式,然后再将它添加到附件中,搞懂了这个就好办了。
1.读取文件
这里我们需要构造一个base64的一个数据流读取文件:
msg6=MIMEMultipart()txt=MIMEText(open('fd.txt','rb').read(), 'base64', 'utf-8')
2.设置传输类型
txt["Content-Type"] = 'application/octet-stream'
3.设置附件名称
txt["Content-Disposition"] = 'attachment; filename = "fd.txt" '
4.将文件添加到附件中
msg6.attach(txt)
最后就成功将文件添加到了附件中了。
项目总结
以上便是我对邮件发送的所有感悟了,另外如果你想将邮件传输时的过程直观展示出来的话只需在邮件服务器登陆的前一句加上:
sm.set_debuglevel(1)
这样便可以将所有传输过程打印在终端了。通过对邮件的学习,可以极大地便利我们的生活,你可以使用邮件来给你设置一个计划表,通过程序实现,每天按时发送邮件,是不是很高逼格了,希望今天这篇文章能让大家对邮件有个全新的认识。
The above is the detailed content of Teach you step by step how to use Python to easily send emails. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

To create a Python virtual environment, you can use the venv module. The steps are: 1. Enter the project directory to execute the python-mvenvenv environment to create the environment; 2. Use sourceenv/bin/activate to Mac/Linux and env\Scripts\activate to Windows; 3. Use the pipinstall installation package, pipfreeze>requirements.txt to export dependencies; 4. Be careful to avoid submitting the virtual environment to Git, and confirm that it is in the correct environment during installation. Virtual environments can isolate project dependencies to prevent conflicts, especially suitable for multi-project development, and editors such as PyCharm or VSCode are also

Install the corresponding database driver; 2. Use connect() to connect to the database; 3. Create a cursor object; 4. Use execute() or executemany() to execute SQL and use parameterized query to prevent injection; 5. Use fetchall(), etc. to obtain results; 6. Commit() is required after modification; 7. Finally, close the connection or use a context manager to automatically handle it; the complete process ensures that SQL operations are safe and efficient.

Use multiprocessing.Queue to safely pass data between multiple processes, suitable for scenarios of multiple producers and consumers; 2. Use multiprocessing.Pipe to achieve bidirectional high-speed communication between two processes, but only for two-point connections; 3. Use Value and Array to store simple data types in shared memory, and need to be used with Lock to avoid competition conditions; 4. Use Manager to share complex data structures such as lists and dictionaries, which are highly flexible but have low performance, and are suitable for scenarios with complex shared states; appropriate methods should be selected based on data size, performance requirements and complexity. Queue and Manager are most suitable for beginners.

Use boto3 to upload files to S3 to install boto3 first and configure AWS credentials; 2. Create a client through boto3.client('s3') and call the upload_file() method to upload local files; 3. You can specify s3_key as the target path, and use the local file name if it is not specified; 4. Exceptions such as FileNotFoundError, NoCredentialsError and ClientError should be handled; 5. ACL, ContentType, StorageClass and Metadata can be set through the ExtraArgs parameter; 6. For memory data, you can use BytesIO to create words

PythonlistScani ImplementationAking append () Penouspop () Popopoperations.1.UseAppend () Two -Belief StotetopoftHestack.2.UseP OP () ToremoveAndreturnthetop element, EnsuringTocheckiftHestackisnotemptoavoidindexError.3.Pekattehatopelementwithstack [-1] on

Use the Pythonschedule library to easily implement timing tasks. First, install the library through pipinstallschedule, then import the schedule and time modules, define the functions that need to be executed regularly, then use schedule.every() to set the time interval and bind the task function. Finally, call schedule.run_pending() and time.sleep(1) in a while loop to continuously run the task; for example, if you execute a task every 10 seconds, you can write it as schedule.every(10).seconds.do(job), which supports scheduling by minutes, hours, days, weeks, etc., and you can also specify specific tasks.

EnsurePythonisinstalledandaddedtoPATHbycheckingversioninterminal;2.Savefilewith.pyextension;3.UseCtrl Btorunviadefaultbuildsystem;4.CreateacustombuildsystemifneededbygoingtoTools>BuildSystem>NewBuildSystem,enteringthecorrectcmdforyourPythonvers

Usetracemalloctotrackmemoryallocationsandidentifyhigh-memorylines;2.Monitorobjectcountswithgcandobjgraphtodetectgrowingobjecttypes;3.Inspectreferencecyclesandlong-livedreferencesusingobjgraph.show_backrefsandcheckforuncollectedcycles;4.Usememory_prof
