Php check email log

Большой Мануал, часть 25: логгируем вызовы mail() из php.

Исторически большая часть вирусни для php занимается именно тем, что шлёт спам. Навскидку я бы оценил количество этой вирусни в половину от всей. Поэтому логгирование вызовов mail() сильно сокращает время на поиск активной части вирусни. Да и просто для дебага «почему письмо не шлется» удобно. Тем более, что в php с версии 5.3 всё же прикрутили неплохое логгирование, которое указывает конкретный php-файл и строчку, где был вызов.
Но, сами понимаете, если бы всё было просто, статью писать я бы не стал. Лог-то прекрасно пишется, если просто включить настройку mail.log, но пишется он от имени пользователя, под которым запущен сам скрипт (соответственно, под апачем скорее всего www-data). А если каждый сайт под своим пользователем? Соответственно, все мануалы пестрят чем-то вроде «создайте файл /var/log/php-mail.log, сделайте chmod 777». В принципе, незачем читать его кому-либо, кроме рута и группы adm, как это принято для всех логов, куда может попасть приватная инфа.
Поэтому отправлять лог мы будем не в файл, а в syslog. Что характерно, официальная документация на php.net об этом не напоминает, да и вообще пришлось поискать, как такое сделать (сначала я пытался сделать mail.log = /dev/log). В итоге, конечно, ничего сложного.
Сначала создаём каталог и файл для лога (вообще каталог не обязательно, я для аккуратности):

Читайте также:  All java access modifiers

root@server:~# mkdir /var/log/php-mail/; chown root:adm /var/log/php-mail/; chmod 750 /var/log/php-mail/

root@server:~# touch /var/log/php-mail/mail.log; chown root:adm /var/log/php-mail/mail.log; chmod 640 /var/log/php-mail/mail.log

Далее заводим ini-файл для php, который включит логгирование (я пишу пример для apache, для fpm/cli просто положите по аналогии в соответствующие каталоги). Для php 5.X в debian файл следует поместить в /etc/php5/apache2/conf.d/90-mail-log.ini, для php7.0 — в /etc/php/7.0/apache2/conf.d/90-mail-log.ini, для 7.2 (если у вас пакет от Ondrej) — в /etc/php/7.2/apache2/conf.d/90-mail-log.ini
Содержимое файла (можете, в принципе, вписать в сам php.ini, но это не всегда удобно):

Далее настраиваем rsyslog (он стоит по умолчанию в debian, для остальных сами гляньте, как откладывать в файл строчки по вхождению), чтобы нужная нам информация попадала в отдельный лог. Кстати, сойдёт за пример, как писать отдельный лог для любых строчек с каким-либо вхождением (в данном случае — «mail()»). Например, в файл /etc/rsyslog.d/99-php-maillog.conf

Почти всё, остаётся только написать конфиг для logrotate, чтобы случайно не забить всё место. Ротировать будем при достижении файлом определенного размера (size 100M). Пишем, например, в /etc/logrotate.d/php-mail

/var/log/php-mail/mail.log <
rotate 7
size 100M
copytruncate
create 0640 root adm
compress
missingok
notifempty
>

Всё, осталось только отрестартить нужные демоны:

Теперь у нас есть лог, в который могут писать любые сайты вне зависимости от пользователя, под которым сайт работает. Прочитать этот лог могут только root и пользователи группы adm, а сам лог изредка ротируется.
Строчки в логе будут выглядеть примерно так:

May 22 14:27:49 dev apache2: [22-May-2018 14:27:49 UTC] mail() on [/home/dev2/data/www/some_file.php:18]: To: example@example.com — Headers:

Источник

How to Check the Status of Emails Sent by Your Apps

Your server uses Postfix to deliver mail. When PHP sends mail, it actually hands the email off to Postfix, which does the actual delivery of the mail.

To see the status of emails being sent by your PHP apps, such as WordPress, you can look in the global Postfix mail log.

Postfix Mail Log Location

To view the Postfix log file, SSH or SFTP into your server as root and open this file:

If that log file is empty, you might instead find the Postfix log messages in:

Also note that these log files are regularly rotated, so for older log entries, you may need to look in files such as:

Reading the Postfix Mail Log

For each email sent, multiple lines will appear in the log file, such as:

Feb 19 03:55:32 ip-10-161-74-52 postfix/pickup[11504]: BE78A40083: uid=1001 from= Feb 19 03:55:32 ip-10-161-74-52 postfix/cleanup[12386]: BE78A40083: message-id= Feb 19 03:55:32 ip-10-161-74-52 postfix/qmgr[6843]: BE78A40083: from=, size=300, nrcpt=1 (queue active) Feb 19 03:55:32 ip-10-161-74-52 postfix/smtp[12388]: connect to ASPMX.L.GOOGLE.com[2607:f8b0:400e:c03::1a]:25: Network is unreachable Feb 19 03:55:33 ip-10-161-74-52 postfix/smtp[12388]: BE78A40083: to=, relay=ASPMX.L.GOOGLE.com[74.125.25.26]:25, delay=0.7, delays=0.03/0/0.11/0.56, dsn=2.0.0, status=sen t (250 2.0.0 OK 1392782133 gx4si20423908pbc.51 - gsmtp) Feb 19 03:55:33 ip-10-161-74-52 postfix/qmgr[6843]: BE78A40083: removed

Your log will look different for each email. In the particular example above, Postfix tried to connect to Gmail’s SMTP servers using IPv6, failed, and then succeeded with IPv4. The email was successfully sent and removed from the local mail queue.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

WPChill/check-email

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

readme.txt

=== Check & Log Email === Contributors: wpchill, silkalns, giucu91 Tags: check, test, email, smtp, pop, send, delivery Requires at least: 5.0 Tested up to: 6.1 Stable tag: 1.0.7 Check & Log email allows you to test if your WordPress installation is sending emails correctly by sending a test email to an address of your choice. Allows overriding of email headers and carbon copying to another address. == Description == In need of a tool that allows you to easily log and view all emails sent from WordPress? Check & Log might be just the solution for that. This WordPress plugin helps you store sent emails for auditing purposes, as well as debug email related problems in your WordPress site. Works best on eCommerce websites that have been created with WooCommerce or Easy Digital Downloads. Some of its features include: - Test email sending - if you’re not sure whether WordPress is sending emails, you can use this plugin to find out. The process is very simple: you need to choose an address that will receive a simple test email. You can even override the custom header with your own values, to avoid any other issues. - Viewing logged emails - they can be viewed from the admin interface, as they are stored in a separate table. You get the option to filter them based on subject, email, date, etc. - Deleting logged emails - you can delete them by going to the admin interface. You can either delete them in bulk or selectively - by date, email, or subject. - Ability to change the "mail from" email address, "mail from name" and override default email WordPress addresses. == Installation == Install the plugin from the plugin repository and activate. == Frequently Asked Questions == = How do I use it? = Check the WordPress Admin Dashboard for "Check & Log Email" menu item. = Why did you write this plugin? = Someone using one of my other plugins had trouble with emails not being sent. I knocked this together to help him (and anyone else). == Screenshots == 1. Check & Log Email - Status 2. Check & Log Email - View Logs 3. Check & Log Email - Settings == Changelog == = v1.0.7 - 08/03/2022 = - Fixed: Incompatibility with Post SMTP ( [#51]( #51) ) = v1.0.6 - 02/05/2022 = - Fixed: Security, sanitization and escaping = v1.0.5 - 10/03/2022 = - Fixed: Replaced deprecated jQuery code ( #32 ) - Fixed: HTML code was being shown in dashboard widget ( #33 ) - Added: Tabs and grouped settings by tabs ( #37 ) - Added: Quick install WP SMTP plugin from settings ( #37 ) = v1.0.4 - 28/10/2021 = - Fixed: URL got too long when bulk deleting email logs. (#30) - Fixed: Sanitization and Escaping = v1.0.3 - 24/09/2021 = - Fixed: Secutiry issue = v1.0.2 - 16/06/2021 = - Added: From column in Email Logs. ( #24 ) = v1.0.2 - 16/06/2021 = - Added: Translation for roles and notices. ( #10 ) - Added: Headers of the emails in the view log tab. ( #12 ) - Fixed: Admin subpages link bug. ( #9 ) - Fixed: Incompatibility with DIVI Theme. We enqued our JS only on Logs Page. ( #13 ) - Fixed: Incompatibility with WpLogging plugin. ( #8 ) - Fixed: Error by adding unique prefixes for Check-Email functions. ( #16 ) - Fixed: Redirect error when using custom folder structure for WP Core. ( #21 ) - Fixed: Deprecated jQuery functions. = 1.0.1 = * Fixed admin menu capabilities. * Rezolved incompatibility with Wp Mail Logging. = 1.0.0 = * Added Email Logs for all the emails sent through WordPress. = 0.6.1 = Added feedback form. Improved CSS backend. = 0.6.0 = Fixed loopback error. = 0.5.7 = Added support for the wp_mail_from filter = 0.5.6 = Tested with WordPress 5.1.1 = 0.5.5 = Fixed typo (sorry sorry sorry) = 0.5.4 = Added FAQ about the location of the tool in the WordPress admin area = 0.5.3 = Fixed deprecation error messages. Tested with 4.7.2. = 0.5.2 = Fixed un-encoded output related to XSS bug = 0.5.1 = Properly fixed XSS vulnerability (apologies) = 0.5 = Fixed XSS vulnerability found by Antonis Manaras = 0.4 = Added more information from php.ini, fixed incorrect textdomains = 0.3 = Moved the page to the Tools menu = 0.2 = Now displays SMTP server name = 0.1.3 = Fixed version number = 0.1.2 = Fixed bug in Plugin Register caused by latest version of WordPress = 0.1.1 = Fixed typo in plugin name = 0.1 = Initial version

Источник

Оцените статью