搜索
首页后端开发Python教程如何使用 Gmail 的免费 SMTP 邮件服务器 API 在 Python 中发送电子邮件

这是您开始使用 Python 发送电子邮件的最简单方法,仅使用 smtplib 和 email 两个库。

在此示例中我们将使用 Gmail 的免费 RESTful API。

这是代码

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

message = MIMEMultipart()
message["To"] = 'To line here.'
message["From"] = 'From line here.'
message["Subject"] = 'Subject line here.'

title = '<b> Title line here. </b>'
messageText = MIMEText('''Message body goes here.''','html')
message.attach(messageText)

email = 'Your Gmail address here.'
password = 'Your app password here.'

server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo('Gmail')
server.starttls()
server.login(email,password)
fromaddr = 'From line here.'
toaddrs  = 'Address you send to.'
server.sendmail(fromaddr,toaddrs,message.as_string())

server.quit()

代码如何工作?

首先,我们导入 smtplib,然后分别从 email.mime.multipart 和 email.mime.text 导入 MIMEMultipart 和 MIMEText:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

然后我们调用 MIMEMultiPart() 并将其实例化为变量 Message。然后,我们为每个变量赋予一个字符串值,即消息、收件人、发件人和主题,它应该如下所示:

Message = MIMEMultipart()
Message["To"] = 'To line here.'
Message["From"] = 'From line here.'
Message["Subject"] = 'Subject line here.'

我们还将通过 title 变量为电子邮件提供标题,并通过 MIMEText() 添加消息,并将其实例化到变量 messageText,最后使用 Attach() 函数将电子邮件消息附加到主变量 Message,它应该看起来像这样:

title = '<b> Title line here. </b>'
messageText = MIMEText('''Message body goes here.''','html')
Message.attach(messageText)

让我们添加我们的 Gmail 地址和应用程序密码,如果您不知道如何获取,请单击此处的链接:

email = 'Your Gmail address here.'
password = 'Your App password here.'

然后我们必须连接到 Gmail 的 SMTP 服务器,我们将使用 smtplib 库来完成此操作,并且我们需要两个变量,即我们要连接的服务器和端口 smtp.gmail.com和 587 分别。

使用 smtplib 库,我们将调用 SMTP 函数并添加服务器和端口变量作为其参数,它应该如下所示:

smtplib.SMTP('smtp.gmail.com:587') (不要忘记它们之间的 :)

然后我们将其实例化到变量服务器:

server = smtplib.SMTP('smtp.gmail.com:587')

然后我们使用 server.ehlo('Gmail') 添加一条 ehlo 语句,这应该是您的域名,这在将电子邮件发送到另一个支持 ESMTP 的邮件服务器时很有用,让我们保持简单,只需输入 Gmail:

server.ehlo('Gmail')

我们还可以使用 server.starttls() 启动 TLS 协议,这告诉邮件服务器我们要通过安全连接发送电子邮件:

server.starttls()

然后我们将使用此行登录邮件服务器:

server.login(email,password)

让我们分别使用 fromaddr 和 toaddrs 添加发件人地址和收件人地址:

fromaddr = 'Your Gmail address.'
toaddrs  = 'Destination address.'

最后,我们使用 server.sendmail(fromaddr,toaddrs,message.as_string()) 发送电子邮件,并使用 server.quit() 关闭与邮件服务器的连接:

server.sendmail(fromaddr,toaddrs,message.as_string())
server.quit()

将其保存在名为 send_email.py 的文件中,如果您使用的是 Linux,则打开终端;如果您使用的是 Windows,则打开命令提示符,然后使用 python send_email.py 启动它,您应该会看到以下内容:

How to Send Emails in Python Using Gmail’s Free SMTP Mail Server API

如果没有任何反应,那么好消息它正在工作!

您的目标邮箱应该已收到一封电子邮件,这是我收到的:

How to Send Emails in Python Using Gmail’s Free SMTP Mail Server API

使用 Python 和 Gmail 的免费 SMTP 服务器发送电子邮件是在 Python 代码中开始发送电子邮件的最简单方法,这正是我在构建第一个在线业务时所做的事情。您可以在这里阅读更多相关信息。

以上是如何使用 Gmail 的免费 SMTP 邮件服务器 API 在 Python 中发送电子邮件的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
列表和阵列之间的选择如何影响涉及大型数据集的Python应用程序的整体性能?列表和阵列之间的选择如何影响涉及大型数据集的Python应用程序的整体性能?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

说明如何将内存分配给Python中的列表与数组。说明如何将内存分配给Python中的列表与数组。May 03, 2025 am 12:10 AM

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

您如何在Python数组中指定元素的数据类型?您如何在Python数组中指定元素的数据类型?May 03, 2025 am 12:06 AM

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

什么是Numpy,为什么对于Python中的数值计算很重要?什么是Numpy,为什么对于Python中的数值计算很重要?May 03, 2025 am 12:03 AM

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

讨论'连续内存分配”的概念及其对数组的重要性。讨论'连续内存分配”的概念及其对数组的重要性。May 03, 2025 am 12:01 AM

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

您如何切成python列表?您如何切成python列表?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

在Numpy阵列上可以执行哪些常见操作?在Numpy阵列上可以执行哪些常见操作?May 02, 2025 am 12:09 AM

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,减法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Python的数据分析中如何使用阵列?Python的数据分析中如何使用阵列?May 02, 2025 am 12:09 AM

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境