0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Python3: POP3 でメールの受信

Posted at

次の記事を参考にしました。
Pythonでメール受信; poplibのサンプルコード

get_pop3.py
# ! /usr/bin/python
#
#	get_pop3.py
#
#						Dec/09/2020
#
# --------------------------------------------------------------------
import os
import sys
import base64
import email
import poplib
import ssl
from email.header import decode_header, make_header
from dotenv import load_dotenv

# --------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
dotenv_path = '.env'
load_dotenv(dotenv_path)
#
server= os.environ.get("SERVER")
usr= os.environ.get("USR")
password= os.environ.get("PASSWORD")

port = 995

context = ssl.create_default_context()
popclient = poplib.POP3_SSL(server, port, timeout=10, context=context)
popclient.set_debuglevel(0)


auth_method = "user"

popclient.user(usr)
popclient.pass_(password)


download_num = 1
msg_list = []
msg_num = popclient.stat()[0]
sys.stderr.write("msg_num = %d\n" % msg_num)

if msg_num <= download_num:
	 download_num = msg_num
for i in range(download_num):
	 msg_bytes = b""
	 for line in popclient.retr(download_num)[1]:
		  msg_bytes += line + b"\n"
	 msg_list.append(email.message_from_bytes(msg_bytes))
popclient.quit()


for msg in msg_list:
	from_addr = str(make_header(decode_header(msg["From"])))
	subject = str(make_header(decode_header(msg["Subject"])))
	print("From:{}".format(from_addr))
	print("Subject:{}".format(subject))
	print()

	if msg.is_multipart() is False:
		payload = msg.get_payload(decode=True)
		charset = msg.get_content_charset()
		if charset is not None:
			payload = payload.decode(charset, "ignore")
		print(payload)
		print()
	else:
		for part in msg.walk():
			payload = part.get_payload(decode=True)
			if payload is None:
				continue
			charset = part.get_content_charset()
			if charset is not None:
				payload = payload.decode(charset, "ignore")
				print(payload)
				print()
#
sys.stderr.write("*** 終了 ***\n")
# --------------------------------------------------------------------
.env
SERVER = 'mail.example.com'
USR = '*****@example.com'
PASSWORD = '*********'

実行方法

./get_pop3.py

次の環境で動作を確認しました。

$ uname -a
Linux iwata 5.8.0-31-generic #33-Ubuntu SMP Mon Nov 23 18:44:54 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
$ python --version
Python 3.8.6

imap で受信する方法はこちら
python でメールの受信

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?