6
6

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.

PHP でメールの受信

Last updated at Posted at 2017-11-26

PHP で imap サーバーからメールを受信する方法です。

imap_get.php
#! /usr/bin/php
<?php
// --------------------------------------------------------------------
/*

	imap_get.php

					Nov/26/2017


*/
// --------------------------------------------------------------------
fputs (STDERR,"*** 開始 ***\n");

$server = 'imap.mail.yahoo.co.jp';
$port = 993;
$user = 'xxxxxxx';
$password = 'yyyyyy';

$mailBox = imap_open('{' . $server . ':' . $port . '/novalidate-cert/imap/ssl}' . "INBOX", $user, $password);
if (!$mailBox) {
	echo "接続失敗\n";
}

$messageIds = imap_search($mailBox, 'ALL');

print_r($messageIds);

foreach($messageIds as $messageId) {
	$header = imap_headerinfo($mailBox, $messageId);

	$subject = mb_decode_mimeheader($header->subject);

	echo "Subject: " . $subject . "\n";

	$body = imap_fetchbody($mailBox, $messageId, 1, FT_INTERNAL);
	$body = trim($body);

	echo "Body: " . $body . "\n";
}

fputs (STDERR,"*** 終了 ***\n");
// --------------------------------------------------------------------
?>

Arch Linux でのライブラリーのインストール方法

sudo pacman -S php-imap

設定ファイルのコメントアウト

/etc/php/php.ini
(省略)
extension=imap
(省略)

Ubuntu でのライブラリーのインストール方法

sudo apt install php-imap

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

$ uname -a
Linux iwata 5.4.0-42-generic #46-Ubuntu SMP Fri Jul 10 00:24:02 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux

$ php --version
PHP 7.4.3 (cli) (built: May 26 2020 12:24:22) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.3, Copyright (c), by Zend Technologies
6
6
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
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?