Php mail on linux

Php mail on linux

(PHP 4, PHP 5, PHP 7, PHP 8)

mail — Отправляет электронную почту

Описание

Отправляет электронную почту.

Список параметров

Получатель, или получатели письма.

Формат этого параметра должен соответствовать » RFC 2822. Несколько примеров:

  • user@example.com
  • user@example.com, anotheruser@example.com
  • User
  • User , Another User

Тема отправляемого письма.

Тема должна соответствовать » RFC 2047.

Каждая строка должна быть отделена символом CRLF (\r\n). Строки не должны быть длиннее 70 символов.

(Только для Windows) Если PHP передаёт данные напрямую SMTP-серверу и в начале строки стоит точка, то она будет удалена. Чтобы избежать этого замените все такие точки на две.

Строка или массив, которые будут вставлены в конец отправляемых заголовков письма.

Обычно используется для добавления дополнительных заголовков (From, Cc, and Bcc). Несколько дополнительных заголовков должны быть разделены CRLF (\r\n). Если для составления этого заголовка используются внешние данные, то они должны быть проверены для избежания инъекций нежелательных заголовков.

Если передан массив, то его ключи будут именами заголовка, а значения значениями.

До PHP 5.4.42 и 5.5.27, параметр additional_headers не имел защиты от инъекции. Так что пользователи должны удостовериться, что передаваемые заголовки безопасны и содержат только заголовки. т.е. не содержат несколько переводов строк подряд, что стартует тело сообщения.

При отправке письмо должно содержать заголовок From . Он может быть установлен с помощью параметра additional_headers , или значение по умолчанию может быть установлено в php.ini .

Если заголовок отсутствует, будет сгенерировано сообщение об ошибке вида Warning: mail(): «sendmail_from» not set in php.ini or custom «From:» header missing . Заголовок From также определяет заголовок Return-Path при отправке напрямую через SMTP (только Windows).

Если сообщения не отправляются, попробуйте использовать только LF (\n). Некоторые агенты пересылки сообщений Unix (особенно » qmail) автоматически заменяют LF на CRLF (что приводит к двойному CR, если использовалось CRLF). Используйте эту меру в крайнем случае, так как это нарушает » RFC 2822.

Параметр additional_params может быть использован для передачи дополнительных флагов в виде аргументов командной строки для программы сконфигурированной для отправки писем, указанной директивой sendmail_path . Например, можно установить отправителя письма при использовании sendmail с помощью опции -f .

Параметр автоматически экранируется функцией escapeshellcmd() , чтобы не допустить выполнение команд. Но escapeshellcmd() позволяет добавлять дополнительные параметры. В целях безопасности рекомендуется проверять и очищать этот параметр.

Так как escapeshellcmd() применяется автоматически, то нельзя использовать некоторые символы, допустимые к использованию в email-адресах некоторыми RFC. mail() не допускает такие символы, поэтому в программах, в которых они требуются, рекомендуется использовать альтернативы для их отправки (например фреймворки или библиотеки).

Пользователь, под которым работает веб-сервер должен быть добавлен в список доверенных в конфигурации sendmail для того чтобы избежать добавления заголовка ‘X-Warning’ при указании отправителя с помощью опции (-f). Для пользователей sendmail — это файл /etc/mail/trusted-users .

Возвращаемые значения

Возвращает true , если письмо было принято для передачи, иначе false .

Важно заметить, что то что письмо было принято для передачи вовсе НЕ означает что оно достигло получателя.

Список изменений

Версия Описание
7.2.0 Параметр additional_headers может принимать значения типа массив.

Примеры

Пример #1 Отправка письма.

Использование функции mail() для отправки простого письма:

// Сообщение
$message = «Line 1\r\nLine 2\r\nLine 3» ;

// На случай если какая-то строка письма длиннее 70 символов мы используем wordwrap()
$message = wordwrap ( $message , 70 , «\r\n» );

// Отправляем
mail ( ‘caffeinated@example.com’ , ‘My Subject’ , $message );
?>

Пример #2 Отправка письма с дополнительными заголовками.

Добавление простых заголовков, сообщающих почтовому агенту адреса From и Reply-To:

= ‘nobody@example.com’ ;
$subject = ‘the subject’ ;
$message = ‘hello’ ;
$headers = ‘From: webmaster@example.com’ . «\r\n» .
‘Reply-To: webmaster@example.com’ . «\r\n» .
‘X-Mailer: PHP/’ . phpversion ();

mail ( $to , $subject , $message , $headers );
?>

Пример #3 Отправка письма с дополнительными заголовками, переданными массивом

В этом примере посылается то же письмо, что и в примере выше, но дополнительные заголовки задаются массивом (доступно с PHP 7.2.0).

= ‘nobody@example.com’ ;
$subject = ‘the subject’ ;
$message = ‘hello’ ;
$headers = array(
‘From’ => ‘webmaster@example.com’ ,
‘Reply-To’ => ‘webmaster@example.com’ ,
‘X-Mailer’ => ‘PHP/’ . phpversion ()
);

mail ( $to , $subject , $message , $headers );
?>

Пример #4 Отправка письма с дополнительными аргументами командной строки.

Параметр additional_params может быть использован для передачи дополнительных параметров программе, используемой для отправки писем с помощью директивы sendmail_path .

Пример #5 Отправка HTML-сообщения

С помощью функции mail() также можно отправить и HTML-письмо.

// несколько получателей
$to = ‘johny@example.com, sally@example.com’ ; // обратите внимание на запятую

// тема письма
$subject = ‘Birthday Reminders for August’ ;

// текст письма
$message = ‘

Birthday Reminders for August

Источник

How To Get PHP mail() Working On Ubuntu 20.04, 18.04 & 16.04

In this article we are going to install and configure Postfix to allow our applications to use the PHP mail() function. Tested and working on Ubuntu 20.04, 18.04 & 16.04.

Introduction

If you’re running your own webserver and expect it to send email via PHP mail() without issue, you are going to have a bad time.

Since I wrote this article in 2017, email providers have become very strict on who they will receive email from. Back in 2017, the massive email services such as Gmail and Office 365 would reluctantly accept emails from cloud instances such as DigitalOcean.

I have observed over the past years a tightening of spam filters, preventing PHP mail() emails from ever reaching their recipients, despite checking all the boxes my end.

So, while this guide will indeed enable your server to send emails out into the ether, the problem now is whether the receiving mail servers will accept or reject them.

Personally, I now relay all emails through a mail provider, be it Mailgun, Sendgrid, or Gmail. You can configure Postfix to send email through an SMTP provider of your choice, which is now my recommendation to guarantee mail delivery.

Please see Step 5 below if your test PHP mail()s are not being delivered to your recipient.

1. Install Postfix

Let’s update the package database first.

Install mailutils , which will automatically install Postfix.

On the first Postfix configuration screen, select OK by pressing TAB and ENTER

Select Internet Site and press ENTER .

System mail name should be your domain name eg. example.com , press ENTER .

Package should now be installed.

2. Configure Postfix

For security reasons, you should instruct Postfix only to process requests to send emails from the server on which it is running.

Edit the Postfix configuration file.

Towards the bottom of the file, find the line inet_interfaces = all . (Press CTRL + W to search)
Change it to:

Save file and exit. (Press CTRL + X , press Y and then press ENTER )

Lastly, let’s restart Postfix.

If you intend on sending email to your own domain, Postfix requires some additional configuration. For example, I want my PHP app to send emails to info@devanswers.co. This will fail if you don’t make some additional changes to your main.cf file.

  • Can’t send mail to own domain. Postfix: status=bounced (unknown user: “user”)

3. Test Postfix

We’ll now send a test email message. Make sure to replace test@example.com with your own email address.

Don’t forget to check your spam folder.

If you still haven’t received any mail after a few minutes, check the mail error log.

If the mail log is empty or doesn’t give enough information, try parsing the syslog. This will return the last 50 entries for postfix.

If the syslog is empty and you still haven’t received any test email, it’s possible that the test email was rejected by the recipient server. You should check to see if anything has bounced back to your mail folder.

Press uppercase G to scroll to the bottom of the file and lowercase q to quit. The $(whoami) variable returns the currently logged in user.

Update Feb 2020: If you are sending to Gmail, Outlook or other large email providers, you may get a bounce error similar to “This message does not have authentication information or fails”. If so, please see article:

  • Postfix Gmail Bounce: This message does not have authentication information or fails to 550-5.7.26 pass authentication checks.

4. Test PHP mail()

If Postfix is working correctly, you should now be able to send mail via PHP mail() .

5. Mail Never Received / Spam Issues

If emails are being rejected by the remote mail provider (such as Gmail or Office 365), or mail is going straight to your email client’s spam folder, you may need to do some additional configuration on your domain (SPF, DKIM, DMARC records) to get past spam filters. Please see:

  • Postfix Gmail Bounce: This message does not have authentication information or fails to 550-5.7.26 pass authentication checks.

However, you may never be able to guarantee delivery of mail via Postfix if you do not route mail through a trusted, external SMTP server. Having had many issues myself over the years sending PHP mail()s from my own cloud server, my recommendation now is to relay mail from Postfix to an external SMTP provider in order to guarantee delivery.

  • Relay Postfix PHP mail() messages through an external SMTP server.
  • Relay Postfix PHP mail() messages through Gmail’s SMTP server .

Let me know if this helped. Follow me on Twitter, Facebook and YouTube, or 🍊 buy me a smoothie.

p.s. I increased my AdSense revenue by 200% using AI 🤖. Read my Ezoic review to find out how.

30 replies

Leave a reply

this solution partially worked

the website said mail was successfully sent
But I got a message bounce back on the email
said: 550 5.7.1
Authentication Required (in reply to end of DATA command)
as I have to authenticate with username / password
before sending emails

how do I authenticate
ubuntu 20.04
php 7.4

Hi,
Excellent tutorial and thank you very much.

I’m hoping you can help with www-data@ when I send with Postfix. This is how it appears now: www-data
I would simply like my email address to show here.

Hey, So I’m seeing some good reviews on this and I would like to try it out. I just have one question (if I may): Why is ‘inet_interfaces’ set to ‘loopback-only’?

It’s for security. We configure Postfix to send and receive emails only from the server on which it is running on—that is, from localhost.

For that to happen, Postfix needs to be configured to listen only on the loopback interface, the virtual network interface that the server uses to communicate internally.

THANK YOU SO MUCH. YOU ARE A GOD SENT PERSON!! i was totally going crazy already its been a week ive been trying to figure this out BUT I just saw this blog post today and omg. Thank you. You are a life saver! 🙂 But there is one problem, like its not a verified email like google says: “Be careful with this message
Gmail could not verify that it actually came from ____@gmail.com. Avoid clicking links, downloading attachments, or replying with personal information.” If you can help me on how to fix this? Anyways 1000000 times Thank you.

postfix/smtp[21099]: connect to mx01.mail.icloud.com[17.57.154.6]:25: Connection timed out im seeing this in AWS

Ubuntu 16.04 in July 2020:
ignores -y in “sudo apt install -y mailutils” (man apt lacks mention of -y)
the postfix configuration screen fails to appear.
main.cf does not exist in /etc/postfix (instead it’s main.cf.proto)
Same findings after sudo apt-get install mailutils”

Thanks Tom. I’ll need to test this on 16.04 again when I get the chance.

What happens if you run sudo apt install postfix

Thank you so much! Solved my mail problems 🙂

Источник

Php mail on linux

PHPMailer – A full-featured email creation and transfer class for PHP

  • Probably the world’s most popular code for sending email from PHP!
  • Used by many open-source projects: WordPress, Drupal, 1CRM, SugarCRM, Yii, Joomla! and many more
  • Integrated SMTP support – send without a local mail server
  • Send emails with multiple To, CC, BCC and Reply-to addresses
  • Multipart/alternative emails for mail clients that do not read HTML email
  • Add attachments, including inline
  • Support for UTF-8 content and 8bit, base64, binary, and quoted-printable encodings
  • SMTP authentication with LOGIN, PLAIN, CRAM-MD5, and XOAUTH2 mechanisms over SMTPS and SMTP+STARTTLS transports
  • Validates email addresses automatically
  • Protects against header injection attacks
  • Error messages in over 50 languages!
  • DKIM and S/MIME signing support
  • Compatible with PHP 5.5 and later, including PHP 8.1
  • Namespaced to prevent name clashes
  • Much more!

Why you might need it

Many PHP developers need to send email from their code. The only PHP function that supports this directly is mail() . However, it does not provide any assistance for making use of popular features such as encryption, authentication, HTML messages, and attachments.

Formatting email correctly is surprisingly difficult. There are myriad overlapping (and conflicting) standards, requiring tight adherence to horribly complicated formatting and encoding rules – the vast majority of code that you’ll find online that uses the mail() function directly is just plain wrong, if not unsafe!

The PHP mail() function usually sends via a local mail server, typically fronted by a sendmail binary on Linux, BSD, and macOS platforms, however, Windows usually doesn’t include a local mail server; PHPMailer’s integrated SMTP client allows email sending on all platforms without needing a local mail server. Be aware though, that the mail() function should be avoided when possible; it’s both faster and safer to use SMTP to localhost.

Please don’t be tempted to do it yourself – if you don’t use PHPMailer, there are many other excellent libraries that you should look at before rolling your own. Try SwiftMailer , Laminas/Mail, ZetaComponents etc.

This software is distributed under the LGPL 2.1 license, along with the GPL Cooperation Commitment. Please read LICENSE for information on the software availability and distribution.

PHPMailer is available on Packagist (using semantic versioning), and installation via Composer is the recommended way to install PHPMailer. Just add this line to your composer.json file:

Note that the vendor folder and the vendor/autoload.php script are generated by Composer; they are not part of PHPMailer.

If you want to use the Gmail XOAUTH2 authentication class, you will also need to add a dependency on the league/oauth2-client package in your composer.json .

Alternatively, if you’re not using Composer, you can download PHPMailer as a zip file, (note that docs and examples are not included in the zip file), then copy the contents of the PHPMailer folder into one of the include_path directories specified in your PHP configuration and load each class file manually:

If you’re not using the SMTP class explicitly (you’re probably not), you don’t need a use line for the SMTP class. Even if you’re not using exceptions, you do still need to load the Exception class as it is used internally.

PHPMailer 5.2 (which is compatible with PHP 5.0 — 7.0) is no longer supported, even for security updates. You will find the latest version of 5.2 in the 5.2-stable branch. If you’re using PHP 5.5 or later (which you should be), switch to the 6.x releases.

Upgrading from 5.2

The biggest changes are that source files are now in the src/ folder, and PHPMailer now declares the namespace PHPMailer\PHPMailer . This has several important effects – read the upgrade guide for more details.

While installing the entire package manually or with Composer is simple, convenient, and reliable, you may want to include only vital files in your project. At the very least you will need src/PHPMailer.php. If you’re using SMTP, you’ll need src/SMTP.php, and if you’re using POP-before SMTP (very unlikely!), you’ll need src/POP3.php. You can skip the language folder if you’re not showing errors to users and can make do with English-only errors. If you’re using XOAUTH2 you will need src/OAuth.php as well as the Composer dependencies for the services you wish to authenticate with. Really, it’s much easier to use Composer!

A Simple Example

You’ll find plenty to play with in the examples folder, which covers many common scenarios including sending through gmail, building contact forms, sending to mailing lists, and more.

If you are re-using the instance (e.g. when sending to a mailing list), you may need to clear the recipient list to avoid sending duplicate messages. See the mailing list example for further guidance.

That’s it. You should now be ready to use PHPMailer!

PHPMailer defaults to English, but in the language folder you’ll find many translations for PHPMailer error messages that you may encounter. Their filenames contain ISO 639-1 language code for the translations, for example fr for French. To specify a language, you need to tell PHPMailer which one to use, like this:

We welcome corrections and new languages – if you’re looking for corrections, run the PHPMailerLangTest.php script in the tests folder and it will show any missing translations.

Start reading at the GitHub wiki. If you’re having trouble, head for the troubleshooting guide as it’s frequently updated.

Examples of how to use PHPMailer for common scenarios can be found in the examples folder. If you’re looking for a good starting point, we recommend you start with the Gmail example.

To reduce PHPMailer’s deployed code footprint, examples are not included if you load PHPMailer via Composer or via GitHub’s zip file download, so you’ll need to either clone the git repository or use the above links to get to the examples directly.

Complete generated API documentation is available online.

You can generate complete API-level documentation by running phpdoc in the top-level folder, and documentation will appear in the docs folder, though you’ll need to have PHPDocumentor installed. You may find the unit tests a good reference for how to do various operations such as encryption.

If the documentation doesn’t cover what you need, search the many questions on Stack Overflow, and before you ask a question about «SMTP Error: Could not connect to SMTP host.», read the troubleshooting guide.

PHPMailer tests use PHPUnit 9, with a polyfill to let 9-style tests run on older PHPUnit and PHP versions.

If this isn’t passing, is there something you can do to help?

Please disclose any vulnerabilities found responsibly – report security issues to the maintainers privately.

Please submit bug reports, suggestions and pull requests to the GitHub issue tracker.

We’re particularly interested in fixing edge-cases, expanding test coverage and updating translations.

If you found a mistake in the docs, or want to add something, go ahead and amend the wiki – anyone can edit it.

If you have git clones from prior to the move to the PHPMailer GitHub organisation, you’ll need to update any remote URLs referencing the old GitHub location with a command like this from within your clone:

Please don’t use the SourceForge or Google Code projects any more; they are obsolete and no longer maintained.

Development time and resources for PHPMailer are provided by Smartmessages.net, the world’s only privacy-first email marketing system.

Donations are very welcome, whether in beer 🍺 , T-shirts 👕 , or cold, hard cash 💰 . Sponsorship through GitHub is a simple and convenient way to say «thank you» to PHPMailer’s maintainers and contributors – just click the «Sponsor» button on the project page. If your company uses PHPMailer, consider taking part in Tidelift’s enterprise support programme.

PHPMailer For Enterprise

Available as part of the Tidelift Subscription.

The maintainers of PHPMailer and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source packages you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact packages you use. Learn more.

  • PHPMailer was originally written in 2001 by Brent R. Matzelle as a SourceForge project.
  • Marcus Bointon ( coolbru on SF) and Andy Prevost ( codeworxtech ) took over the project in 2004.
  • Became an Apache incubator project on Google Code in 2010, managed by Jim Jagielski.
  • Marcus created his fork on GitHub in 2008.
  • Jim and Marcus decide to join forces and use GitHub as the canonical and official repo for PHPMailer in 2013.
  • PHPMailer moves to the PHPMailer organisation on GitHub in 2013.

What’s changed since moving from SourceForge?

Источник

Читайте также:  Sql shell psql windows
Оцените статью