Pythonによるメールの送受信方法
メールを送受信するには、smtplib と poplib モジュールを使用できます。例:
メールを送信します。
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アクセスを有効にしてください。
必要に応じて、上記のコードを変更および拡張できます。