本文主要是介绍Python之邮箱自动发件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在使用python给好友发送邮件时,首先需要下载python中在对模块,以及打开邮箱IMAP/SMTP服务。接下来一步一步介绍读者如何来使用并实现发件。
1.下载python中在对模块
首先键盘点击win+R键,输入pip search smtplib便可以看到smtplib模块下含有那些包,运行后如下所示:
C:\Users\Admin>pip search smtplib
pycopy-smtplib (0.0.1) - Dummy smtplib module for Pycopy
micropython-smtplib (0.0.1) - Dummy smtplib module for MicroPython
secure-smtplib (0.1.1) - Secure SMTP subclasses for Python 2
smtplibaio (2.1.2.post1) - An async version of smtplib
easyemail (0.4.0) - Simple lib abstracting email sending with smtplib.
mailclient (0.2.0) - Simplified use of smtplib for Python. Easy email sending.
xsmtplib (1.0.1.dev0) - An extension of standard smtplib, which supports proxy tunneling
PyEmail (0.0.1) - Python library to send emails using SMTPLIB library
personal (0.1.1) - Easy, secure self notification via email and sms, using smtplib and twilio
py-emails (1.2.0) - Simple wrapper around email and smtplib for composing and sending email messages in anintuitive, simple interface.
drymail (0.0.6) - Drymail is a minimalist wrapper over Python’s existing smtplib and emaillibraries, designed to be friendly but unrestrictive.
ld-smtp (1.0.2) - Este modulo ira realizar o envio de e-mail utilizando o smtplib.
一般我们在发送邮件时,需要使用PyEmail包,接下来输入pip install PyEmail,即可下载该包。
2.获取邮箱的IMAP/SMTP服务授权码
因为我经常使用QQ邮箱,接下来我以QQ邮箱为例,来获取邮箱的IMAP/SMTP服务授权码,首先登陆QQ邮箱,在QQ邮箱界面上方点击设置按钮,如图所示:
在设置界面点击账户,至POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务处,开启IMAP/SMTP服务(邮箱绑定手机号需发验证;邮箱未绑定手机号时,需申请)如图所示:发送的邮件可以设置SSL加密方式,设置POP3/SMTP的SSL加密方式,如下图所示:
3.Python代码如下所示:
import smtplib#导入smtplib库
#从email中导入header用来完成邮箱标题的定义
from email.header import Header
#从emali中导入MIMEText用来完成邮箱内容的定义
from email.mime.text import MIMEText
#发送的邮箱号
my_email = "发送箱"
#发送接收的邮箱
then_email = "收件箱"
#发送的邮箱服务器
email_smtpserver = "smtp.qq.com"
#发送的邮箱号和授权码
my_username = "发送箱"
my_password = "发送箱授权码"
#发送的邮件主题
subject = "云想衣裳花想容"
#发送的邮件正文
email_msg = MIMEText("春风拂槛露华浓","plain","utf-8")
email_msg["subject"] = Header(subject, "utf-8")
#SSL安全连接,465为发送邮件的端口号
smtp = smtplib.SMTP_SSL(email_smtpserver, 465)
#配置发送邮件的用户名和密码
smtp.login(my_username, my_password)
#配置发送邮件、接受邮件和邮件内容
smtp.sendmail(my_email, then_email, email_msg.as_string())
#运行完成后,关闭邮件发送
smtp.quit()
4.运行代码
代码运行后,收件箱收到的邮件如图所示:
看完之后,您学会了吗,欢迎在下方留言哦!
这篇关于Python之邮箱自动发件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!