LoginSignup
13
16

python でメールの受信

Last updated at Posted at 2017-11-26

Python3 で、imap サーバーからメールを受信する方法です。
Yahoo Mail で確認しました。

imap_get.py
#! /usr/bin/python
#
#   imap_get.py
#
#					   Jun/26/2023
#
# --------------------------------------------------------------------
import os
import sys
import ssl
import imaplib
import email
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")
try:
	context = ssl.create_default_context()
#	context = ssl._create_unverified_context()
	imapclient = imaplib.IMAP4_SSL(server, 993, ssl_context=context)
#   sys.stderr.write("*** usr = %s ***\n" % usr)
#   sys.stderr.write("*** password = %s ***\n" % password)
	imapclient.login(usr,password)
	imapclient.select()
	typ, data = imapclient.search(None, 'ALL')
	icount = 0
	for num in data[0].split():
		typ, data = imapclient.fetch(num, '(RFC822)')
		email_message = email.message_from_bytes(data[0][1])
#
		email_from = str(make_header(decode_header(email_message['From'])))
		print(email_from)
		subject = str(make_header(decode_header(email_message['Subject'])))
		print(subject)
		sys.stderr.write(subject + "\n")
		

#		msg_encoding = 'iso-2022-jp'
		msg_encoding = 'utf-8'

		if email_message.is_multipart() == False: # シングルパート
			sys.stderr.write("*** eeee ***\n")
			byt  = bytearray(email_message.get_payload(), msg_encoding)
			body = byt.decode(encoding=msg_encoding)
		else:   # マルチパート
			sys.stderr.write("*** multi part ***\n")
			prt  = email_message.get_payload()[0]
			byt  = prt.get_payload(decode=True)
			try:
#				body = byt.decode(encoding=msg_encoding)
				body = byt.decode("utf-8")
			except Exception as ee:
				sys.stderr.write("*** error *** byt.decode\n")
				sys.stderr.write(str(ee) + '\n')
			sys.stderr.write("*** hhhh ***\n")
#
		print(body)
#
		icount += 1
		if (2 < icount):
			break
	imapclient.close()
	imapclient.logout()
except Exception as ee:
	sys.stderr.write("*** error ***\n")
	sys.stderr.write(str(ee) + '\n')

sys.stderr.write("*** 終了 ***\n")
# --------------------------------------------------------------------
.env
SERVER = 'imap.mail.yahoo.co.jp'
USR = '*****@yahoo.co.jp'
PASSWORD = '*********'

確認したバージョン

$ python --version
Python 3.11.3

Yahoo 以外のサイトで、次のようなエラーが出る時の対策

[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: Hostname mismatch, certificate is not valid for
#       context = ssl.create_default_context()
       context = ssl._create_unverified_context()
13
16
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
13
16