搜尋
首頁後端開發Python教學如何使用Python腳本在Linux中實現郵件發送與接收

如何使用Python腳本在Linux中實現郵件發送與接收

如何使用Python腳本在Linux中實作郵件傳送與接收

在Linux系統中,我們可以使用Python腳本來實作郵件的傳送與接收功能。 Python的smtplib和imaplib模組提供了對應的功能。

一、郵件發送
要實現郵件發送功能,首先需要準備好發送方的郵件地址和SMTP伺服器的相關資訊。以下是一個簡單的範例程式碼:

import smtplib
from email.mime.text import MIMEText

def send_email():
    # 发送方的邮箱地址和授权码
    sender_email = "your_email@gmail.com"
    sender_password = "your_password"
    
    # 接收方的邮箱地址
    receiver_email = "recipient_email@gmail.com"
    
    # 邮件主题和内容
    subject = "Hello from Python Script"
    body = "This is a test email sent from a Python script."
    
    # 创建邮件对象
    message = MIMEText(body, "plain")
    message["Subject"] = subject
    message["From"] = sender_email
    message["To"] = receiver_email
    
    # 发送邮件
    try:
        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.starttls()
        server.login(sender_email, sender_password)
        server.sendmail(sender_email, receiver_email, message.as_string())
        print("Email sent successfully")
    except Exception as e:
        print("Failed to send email. Error:", str(e))
    finally:
        server.quit()

send_email()

在上述程式碼中,我們使用了Gmail的SMTP伺服器來傳送郵件。可根據需要替換為其他SMTP伺服器,同時要注意更改對應的連接埠號碼。

二、郵件接收
要實現郵件接收功能,需要準備接收方的郵箱位址、IMAP伺服器的資訊、登入憑證。以下是一個簡單的範例程式碼:

import imaplib

def receive_email():
    # 接收方的邮箱地址和授权码
    email_address = "recipient_email@gmail.com"
    email_password = "your_password"
    
    try:
        # 连接到IMAP服务器
        mailbox = imaplib.IMAP4_SSL("imap.gmail.com")
        mailbox.login(email_address, email_password)
        
        # 选择邮箱
        mailbox.select("INBOX")
        
        # 搜索并获取最新的邮件
        result, data = mailbox.search(None, "ALL")
        latest_email_id = data[0].split()[-1]
        result, data = mailbox.fetch(latest_email_id, "(RFC822)")
        
        # 解析邮件内容
        email_text = data[0][1].decode("utf-8")
        print("Received email:
", email_text)
    except Exception as e:
        print("Failed to receive email. Error:", str(e))
    finally:
        mailbox.close()
        mailbox.logout()

receive_email()

在上述程式碼中,我們同樣使用了Gmail的IMAP伺服器來接收郵件。同樣可以根據需要替換為其他IMAP伺服器。

以上就是使用Python腳本在Linux中實作郵件發送與接收的基本步驟和程式碼範例。透過這些代碼,我們可以在Linux系統中靈活地發送和接收郵件。希望對您有幫助!

以上是如何使用Python腳本在Linux中實現郵件發送與接收的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python:編譯器還是解釋器?Python:編譯器還是解釋器?May 13, 2025 am 12:10 AM

Python是解釋型語言,但也包含編譯過程。 1)Python代碼先編譯成字節碼。 2)字節碼由Python虛擬機解釋執行。 3)這種混合機制使Python既靈活又高效,但執行速度不如完全編譯型語言。

python用於循環與循環時:何時使用哪個?python用於循環與循環時:何時使用哪個?May 13, 2025 am 12:07 AM

UseeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.forloopsareIdealForkNownsences,而WhileLeleLeleLeleLeleLoopSituationSituationsItuationsItuationSuationSituationswithUndEtermentersitations。

Python循環:最常見的錯誤Python循環:最常見的錯誤May 13, 2025 am 12:07 AM

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐個偏置,零indexingissues,andnestedloopineflinefficiencies

對於循環和python中的循環時:每個循環的優點是什麼?對於循環和python中的循環時:每個循環的優點是什麼?May 13, 2025 am 12:01 AM

forloopsareadvantageousforknowniterations and sequests,供應模擬性和可讀性;而LileLoopSareIdealFordyNamicConcitionSandunknowniterations,提供ControloperRoverTermination.1)forloopsareperfectForeTectForeTerToratingOrtratingRiteratingOrtratingRitterlistlistslists,callings conspass,calplace,cal,ofstrings ofstrings,orstrings,orstrings,orstrings ofcces

Python:深入研究彙編和解釋Python:深入研究彙編和解釋May 12, 2025 am 12:14 AM

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

Python是一種解釋或編譯語言,為什麼重要?Python是一種解釋或編譯語言,為什麼重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

對於python中的循環時循環與循環:解釋了關鍵差異對於python中的循環時循環與循環:解釋了關鍵差異May 12, 2025 am 12:08 AM

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

循環時:實用指南循環時:實用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

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

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

熱門文章

熱工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

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

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器