一、發送郵件
Python作為一門強大的編程語言,可以不僅作為數據處理和Web開發的首選,而且還可以通過使用相應的庫來發送郵件。Python的smtplib庫(簡單郵件傳輸協議庫)是發送電子郵件的常用庫。大多數郵件伺服器都需要經過身份驗證才能發送郵件,因此需要在Python代碼中添加您的郵件伺服器的登錄憑據。
下面是一個使用Python發送電子郵件的示例代碼:
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.image import MIMEImage msg = MIMEMultipart() msg['From'] = 'sender_email_address' msg['To'] = 'recipient_email_address' msg['Subject'] = 'Subject of the Email' body = 'This is the body of the email' msg.attach(MIMEText(body, 'plain')) filename = 'filename.jpg' with open(filename, 'rb') as f: img_data = f.read() img = MIMEImage(img_data, name=filename) msg.attach(img) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login('sender_email_address', 'sender_email_password') text = msg.as_string() server.sendmail('sender_email_address', 'recipient_email_address', text) server.quit()
在上述代碼中,我們使用了SMTP協議發送電子郵件,帶有一個附件。可以發現,我們需要登錄我們的電子郵件帳戶以啟用SMTP連接,並使用名為starttls()的方法來啟用TLS加密。
發送電子郵件也可以通過其他庫,例如yagmail、smtplib等。
二、接收郵件
Python的imaplib(Internet Mail Access Protocol庫)是接收電子郵件的常用庫,對於使用IMAP(Internet Mail Access Protocol)的大多數郵件伺服器,您需要向代碼中添加您的郵件伺服器的登錄憑據。
下面是一個使用Python接收電子郵件列表的示例代碼:
import imaplib import email import os user = 'user_email_address' password = 'user_email_password' imap_url = 'imap.googlemail.com' #Establishing the Connection imap = imaplib.IMAP4_SSL(imap_url) #Login imap.login(user, password) #Fetching the Email Ids imap.select('Inbox') status, messages = imap.search(None, 'ALL') messages = messages[0].split(b' ') print(messages) #Iterating through the email ids and storing fetch data in dictionary for mail in messages: _, msg = imap.fetch(mail, '(RFC822)') for response in msg: if isinstance(response, tuple): msg = email.message_from_bytes(response[1]) subject = msg['subject'] from_ = msg['from'] print(f'Subject: {subject}') print(f'From: {from_}') imap.close() imap.logout()
在上述代碼中,我們使用IMAP協議接收郵件,並顯示了每個郵件的主題和發件人的地址。
三、結論
Python的能力不僅僅在於數據處理和Web開發,還包括發送/接收電子郵件。本文演示了如何使用Python中的smtplib和imaplib庫來發送和接收電子郵件。
以上是關於利用Python實現郵件發送和接收的方法及代碼分享,希望能對初學者或有需要的人有所幫助。
原創文章,作者:OKEL,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/145151.html