溫馨提示×

怎么用python收發郵件

小億
87
2023-11-06 21:18:09
欄目: 編程語言

要使用Python收發郵件,你可以使用內置的smtplibpoplib模塊來發送和接收郵件。下面是一個簡單的示例:

發送郵件:

import smtplib
from email.mime.text import MIMEText

def send_email(sender_email, receiver_email, subject, message, password):
    # 創建郵件內容
    email_message = MIMEText(message)
    email_message['Subject'] = subject
    email_message['From'] = sender_email
    email_message['To'] = receiver_email

    # 發送郵件
    with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
        smtp.starttls()
        smtp.login(sender_email, password)
        smtp.send_message(email_message)

接收郵件:

import poplib
from email.parser import Parser

def receive_email(receiver_email, password):
    # 連接到POP3服務器
    with poplib.POP3('pop.gmail.com') as pop:
        pop.user(receiver_email)
        pop.pass_(password)

        # 獲取郵件列表
        email_list = pop.list()[1]
        for email_info in email_list:
            email_number, _ = email_info.decode().split(' ')
            email_number = int(email_number)

            # 獲取郵件內容
            _, lines, _ = pop.retr(email_number)
            email_content = b'\r\n'.join(lines).decode('utf-8')

            # 解析郵件內容
            email = Parser().parsestr(email_content)

            # 打印郵件主題和發件人
            print("主題:", email['Subject'])
            print("發件人:", email['From'])

注意:在發送郵件之前,你需要在發件人的郵箱設置中啟用SMTP訪問,并生成一個應用密碼(如果使用Gmail)。

在接收郵件之前,你需要在收件人的郵箱設置中啟用POP3訪問。

你可以根據需要對以上代碼進行修改和擴展。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女