4.8.10. Invalid "From" header
Attention!
This problem may occur when sending messages from a web server without authentication and via SMTP with authentication.General information
The problem arises because the message is sent from one mailbox, but when the message body is generated, the "From" header contains the address of a mailbox from a different mail domain that is in no way associated with the domain from which the message is actually being sent. For example, an email is sent from the mailbox mail@example.com, but the "From" header contains an address such as johndoe@gmail.com, which is unrelated to mail@example.com. Such messages will not be delivered.
The address that appears in the header can be specified in the site's code or database, or a script can retrieve it via a form on the site. There is no one-size-fits-all answer to this question; it all depends on the site's code, the CMS used, plugins, and so on.
In addition, this problem may occur when using a redirect in a third-party mail client. In this case, the sender's actual address and the address in the "From" header will differ, and the messages will not be delivered.
When header is considered valid
(*.default-host.net)"|maillog maillog-->|Some recipients have third-party mail domains|from maillog-->|All recipients in your own mail domains|sent from--->|Own mail domain|sent from-->|"*.default-host.net (without authorization)"|sent from-.->|Third-party mail domain|invalid-from invalid-from-.->unsent envelope-sender-.->|Third-party mail domain|invalid-sender invalid-sender-.->unsent mail-->|From site|php-mail-log php-mail-log-->envelope-sender envelope-sender-...->|Sender is set in two different ways|sendmail-exited sendmail-exited-.->php-error-log
When sent from a web server without authorization, the header is considered valid under the following conditions:
- The mail domain from the header added in your account.
- The sender's hosting account and the mail domain in the header belong to the same account.
- If the account belongs to only one of the services and the other is delegated, the header is not considered valid.
- If a sender is specified (either outgoing mail is selected or the
-fparameter is used in the PHP mail function), the mail domain in the header must match the sender's domain. - If no sender is specified, the header must contain the address of your mail domain.
- If neither the sender nor the subject is specified, the header will contain the default mail address in the
*.default-host.netformat.- Our service allows you to send such emails, but delivery is not guaranteed, as recipients may reject them.
When sending via SMTP with authentication, the header is considered valid under the following conditions:
- The mail domain in the header matches the domain of the mailbox from which the message is being sent.
The header is not checked if the mail domains of all recipients belong to the same account as the sender's mail domain (non-delegated).
Where header is set
in script?" } site@{ shape: diamond, label: "Send
from site?" } outgoing@{ shape: diamond, label: "Selected
outgoing
mail?" } cron@{ shape: diamond, label: "Selected
deafult
mailbox?" } subgraph "From" script_mailbox@{ shape: rounded, label: "📝 Address
from script" } outgoing_mailbox@{ shape: rounded, label: "⚙️ Address
from site settings" } cron_mailbox@{ shape: rounded, label: "⚙️ Address
from hosting account
settings" } cron_account@{ shape: rounded, label: "🌐 *.default-host.net" } end smtp------>script_mailbox mail-->script script-->|✅|script_mailbox script-->|❌|site site-->|✅|outgoing outgoing-->|✅|outgoing_mailbox outgoing-->|❌|cron cron-->|✅|cron_mailbox cron-->|❌|cron_account site-->|❌|cron
When sending from a web server without authorization:
- The header is set by the site's scripts (this method takes precedence over the settings in the hosting control panel).
- If the message is sent via the site and the header is not specified in the scripts, the outgoing mail from the site settings is used.
- In all other cases, the default outgoing mail address from the hosting account settings is used.
When sending via SMTP with authentication:
- The header is set by the sending script or the mail client being used.
Consequences
Before sending each email, the system checks the validity of the "From" header. If the header is invalid, the following occurs:
- Sending the email is blocked.
- A record of the sending attempt is added to the unsent emails log.
- The attempt to send the email is included in the statistics for the current day.
- Early the next day, an message with statistics for the previous day is sent to your email.
Only specific messages with incorrect headers are blocked. Messages with a valid "From" header are not affected in any way — they are sent as usual.
Notifications
These are sent to your email early the next day and contain statistics on messages with an incorrect "From" header from the previous day.
You can manage notifications in the notification settings using the "Service restrictions" option.
Diagnostics
A list of logs that can help identify the source of messages with incorrect headers.
When sending from a web server without authorization:
- All attempts to send messages are visible in the site mail log.
- Attempts to send messages via sites are visible in the PHP mail logs (individually for each site).
- All attempts to send messages with invalid headers are visible in the unsent emails log for hosting account.
- Errors related to the PHP mail function when sending messages via sites are visible in the PHP error logs (individually for each site).
When sending via SMTP with authentication:
- All connections made during send attempts are visible in the mailbox connection logs (individually for each mailbox).
- All attempts to send messages with invalid headers are visible in the unsent emails log for mail domain (individually for each mail domain).
If the emails are sent from the site, you can compare the send times with the request times in the site access logs. For example, if a POST request was made to the site’s scripts at the same time an email with an incorrect header was attempted to be sent, it is highly likely that these scripts are related to that email (often these are various contact forms, order forms, etc.).
Solution
If the problem is related to the site, the solution usually comes down to the following:
- Find the script or plugin on the site that handles sending messages.
- Determine what information it substitutes in the "From" header and where it gets it from.
- Ensure that the correct sender is substituted into the script.
In other words, if the script sends a message on behalf of the mail@example.com email address, then the "From" header must also specify that same email address.
You can take action depending on the addresses you see in notifications about emails sent with an incorrect "From" header:
- The "From" header contains one of your domains:
- Check whether the corresponding mail domain is added in your account.
- Make sure the mail domain belongs to the same account as the hosting account from which the message is being sent (delegation does not apply)
- The "From" header contains your mailbox address on a third-party mail service:
- Check the mailing scripts on your site or the settings of your CMS, find this address, and replace it with the mailbox address of one of your mail domains.
- If you want to continue sending messages from the mailbox of a third-party mail service, configure sending via SMTP.
- The "From" header contains various addresses that you don't recognize:
- Check the form handlers on your site or the settings of your CMS, find the place where an incorrect address is being inserted into the header, and make sure that the address of a mailbox on one of your mail domains is inserted instead.
If the problem is related to a redirect in a third-party mail client, follow these steps to resolve it:
- Disable redirects in third-party mail client.
- Organize the delivery of messages to the desired mailbox using one of the following methods:
- Set up a redirect in the control panel.
- Set up a redirect using filters in WebMail.Online or WebMail classic.
Comments
Попытки отправки вы можете увидеть в разделе «Неотправленные письма» — https://adm.tools/hosting/account/0/mail/unsent/, а POST-запросы к форме на вашем сайте — в логах доступа к сайту — https://adm.tools/hosting/account/0/virtual/0/edit/serverlog/
Якщо з якихось причин вони у вас не працюють, можете просто перейти в панелі керування за наступними шляхами:
- Хостинг → Невідправлені листи.
- Хостинг → Мої сайти → ваш сайт → Логи доступу до сайту.
А как сделать так чтобы все же можно было отправлять с другим полем From ?
если в пределах одного домена надо пересылать не регулярно письма как выходить из положения ?
Пример - один наш бухгалтер хочет переслать другому нашему бухгалтеру квитанцию с новой почты. В поле From адрес новой почты.
Уверен, что Thunderbird и The Bat! имеют настройку, которая меняет поведение при Forwarding.
Если хостинг провайдер даст возможность указывать любой From, то вам можно прислать фишинг или вирус, отправив в рамках того же хостинг провайдера письмо на ваш email. И при этом оно пройдет все фильтры у этого провайдера. Вы хоть понимаете, что требованием дать возможность отправлять так почту стреляете себе в ногу и при этом стреляете с пушки?
В вашем случае для решения проблемы должно быть достаточно выбрать созданный на хостинге почтовый ящик в поле «Исходящая почта» в настройках сайта, как предложено в комментарии выше.
Благодарю за разъяснение и помощь.
Если в процессе возникнут трудности, обратитесь в за консультацией в онлайн-чат.
Все работало нормально.
Вы что-то поменяли в настройках хостинга, и теперь заказы с сайта не приходят.
По сути вы своими действиями сломали работу интернет магазина.
Если вы что то поменяли, что из за этого перестал корректно работать интернет магазины ваших клиентов, то будь ласка, исправляйте, решайте проблемы ваших клиентов сами.
Пишите подробную инструкцию для каждого клиента, подключайтесь к исправлению проблемы.
Я уже неделю ищу решения проблемы, созданой вами, а результата ноль.
Почта с интернет магазина как не приходила, так и не приходит.
Чтобы исправить проблему, достаточно корректно настроить отправку почты с сайтов. Если сайт условно называется example.com, то почта должна уходить с адреса с таким же почтовым доменом, а не выдавать себя за gmail.com, outlook.com и т. д.
Если в вашем случае проблема относится к сайту на OpenCart, попробуйте настроить почту по этой инструкции — https://www.ukraine.com.ua/wiki/hosting/cms/opencart/mail/
В случае возникновения трудностей или дополнительных вопросов, обратитесь за консультацией в онлайн-чат.
catalog/controller/information/contact.php
замінив з
$mail->setFrom($this->request->post['email']);
на
$mail->setFrom($this->config->get('config_email'));
поки працює
только через СМТП теперь? у меня не получилось его настроить корректно раньше и нормально работало через встроенную функцию ПХПББ...
Це відповідь ШІ на ситуацію коли провайдер став розсилати повідомлення про ⚠️ Надсилання листів з некоректним заголовком «From».
"Що насправді відбувається?
Ти кажеш, що ні ти, ні модулі сайту нічого не відправляєте. Але лог показує зворотне: відпрацьовує стандартна функція PHP mail() прямо з движка OpenCart: /system/library/mail/mail.php на рядку 77.
Це спам-боти, які шлють повідомлення через твою форму зворотного зв'язку або реєстрації.
Працює це так:
Бот заходить на твій сайт (наприклад, на сторінку «Контакти» або форму відгуків).
Заповнює поля: вписує умовне ім'я «Margie Christiansen», пошту christiansen.margie@gmail.com і якийсь спам-текст.
Натискає «Відправити».
OpenCart за логікою своєї роботи намагається переслати це повідомлення тобі на info@vidnova.shop.
У чому конфлікт із хостингом?
За замовчуванням OpenCart влаштований так: коли хтось пише через форму зв'язку, движок формує лист, де в поле From (Від кого) підставляє пошту клієнта (того самого бота — christiansen.margie@gmail.com), а в полі To (Кому) вказує твою адресу info@'ваш.сайтʼ
Сучасні хостинги (і поштові сервери) таку практику жорстко присікають. Твій сервер не має права відправляти листи від імені gmail.com чи outlook.com — це грубе порушення політик безпеки (SPF, DKIM). Хостинг бачить, що скрипт намагається відправити лист нібито від імені Margie, і блокує його, щоб сервер не потрапив у спам-листи.
Висновок: Твій сайт не зламали (принаймні, цей лог про це не говорить). Це просто спам через стандартну форму, посилений некоректною логікою формування заголовків у самому OpenCart.
Як це правильно виправити?
Рішення складається з двох обов'язкових кроків: технічного (щоб не сварився хостинг) та захисного (щоб припинити спам).
### Крок 1. Виправляємо заголовки From в OpenCart (Технічне рішення)
Тобі потрібно зробити так, щоб сайт відправляв усі листи тільки від імені твоєї офіційної скриньки (info@'ваш.сайтʼ), а пошту клієнта/бота зашивав у заголовок Reply-To (Відповісти сторічці). Тоді хостинг пропустить лист, а коли ти натиснеш «Відповісти» у поштовому клієнті, відповідь піде автору повідомлення.
Оскільки ти використовуєш OpenCart, найкраще переключити відправку з функції Mail на SMTP (якщо ще не зроблено) і підправити логіку:
1) Перехід на SMTP (якщо можливо):
В адмінці OpenCart: Система -> Налаштування -> Редагувати магазин -> вкладка "Пошта".
Зміни "Поштовий протокол" з Mail на SMTP.
Заповни параметри твоєї робочої пошти хостингу (SMTP-сервер, логін, пароль, порт). Сайти на SMTP працюють стабільніше і листи рідше падають у спам.
2) Модифікація коду (виправлення From для Mail/SMTP):
Якщо проблема лишається, потрібно змінити логіку в контролері контактів (catalog/controller/information/contact.php).
Знайди там код, де формується відправка листа адміністратору (зазвичай там є рядок $mail->setFrom($this->request->post['email']);).
Його потрібно змінити так:
PHP
// Замість пошти клієнта ставимо пошту магазину:
$mail->setFrom($this->config->get('config_email'));
// А пошту клієнта записуємо в Reply-To, щоб ти міг йому відповісти:
$mail->setReplyTo($this->request->post['email']);
*Примітка: Якщо оновлюєш код, роби це через OCMOD/відповідний модифікатор, щоб при оновленні сайту правки не злетіли.*
### Крок 2. Закриваємо форми від ботів (Захист від спаму)
Навіть якщо ти виправиш заголовки, боти продовжать забивати твою пошту сміттям. Їх треба відсікти.
* **Встанови Google reCAPTCHA v3 або Cloudflare Turnstile:** Стандартна капча OpenCart (якщо вона там стара) ботами клацається на раз-два. reCAPTCHA v3 або Turnstile від Cloudflare працюють непомітно для користувача, але блокують 99% автоматичного спаму.
* **Перевір усі форми:** Спамити можуть не лише через «Контакти», а й через форму «Купити в 1 клік», «Зворотній дзвінок» або реєстрацію (якщо боти реєструють фейкових користувачів, і сайт шле тобі сповіщення про нового клієнта). Закрий капчею кожну з них.
Виконавши ці два кроки, ти і хостинг заспокоїш, і скриньку від спаму очистиш."
Я для початку обмежився переходом з Mail на SMTP і далі буду дивитись чи робити модифікацію коду та чи ставити reCAPTCHA.
Всім успіхів.
Если у вас письма отправляются с адреса вида wordpress@ваш_сайт, значит на вашем сайте используется WordPress и для него используется почта по умолчанию. В этом случае вам нужно добавить почтовый домен с адресом вашего сайта — https://www.ukraine.com.ua/wiki/mail/domains/order/ — и создать для него почтовый ящик с любым названием — https://www.ukraine.com.ua/wiki/mail/boxes/create/
После этого можно настроить для сайта отправку почты по SMTP — https://www.ukraine.com.ua/wiki/hosting/cms/wordpress/plugins/mail/
В итоге сайт будет отправлять письма от имени реально существующего почтового ящика и проблем с заголовком больше возникать не должно.