搜尋
首頁後端開發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

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境