php exchange send mail
How to send email using PHP PEAR mail and Exchange Server 2016
I need to send an SMTP email over Exchange Server 2016 in PHP using PEAR mail and an authenticated AD user. I found an example online:
When I run this I get the following error:
authentication failure [SMTP: No supported authentication methods (code: 250, response: mail.mydomain.com Hello [192.168.30.254] SIZE 37748736 PIPELINING DSN ENHANCEDSTATUSCODES STARTTLS AUTH GSSAPI NTLM 8BITMIME BINARYMIME CHUNKING)]
At the same time this similar C# application works fine without any problems:
As the C# code works fine, the Exchange Server is correctly configured but PEAR mail cannot authenticate.
How shall I configure PEAR mail and/or Exchange so that this can work? Anonymous SMTP email sending is not an option in this environment.
Update: After BastianW’s comment I succeeded in enabling AUTH LOGIN and now there is a different error:
DEBUG: Recv: 220 mail.mydomain.com Microsoft ESMTP MAIL Service ready at Thu, 3 Aug 2017 15:33:14 +0200
DEBUG: Send: EHLO localhost
DEBUG: Recv: 250-mail.mydomain.com Hello
DEBUG: Recv: 250-SIZE 37748736
DEBUG: Recv: 250-PIPELINING
DEBUG: Recv: 250-ENHANCEDSTATUSCODES
DEBUG: Recv: 250-STARTTLS
DEBUG: Recv: 250-AUTH LOGIN
DEBUG: Recv: 250-8BITMIME
DEBUG: Recv: 250-BINARYMIME
DEBUG: Recv: 250 CHUNKING
DEBUG: Send: AUTH LOGIN
DEBUG: Recv: 334 VXNlcm5hbWU6
DEBUG: Send: cGxcUHJlcGF5LlBsYXRmb3Jt
DEBUG: Recv: 334 UGFzc3dvcmQ6
DEBUG: Send: OTAjMDNiUjFaaGM2SjRU
DEBUG: Recv: 235 2.7.0 Authentication successful
DEBUG: Send: MAIL FROM:
DEBUG: Recv: 250 2.1.0 Sender OK
DEBUG: Recv: 250 2.0.0 Resetting
Why does PEAR mail send RSET which closes the connection when it gets the «Sender OK»?
Sending email with PHP from an SMTP server
I was under the impression that you can send email without SMTP to verify. I know that this mail will propably get filtered out, but that doesn’t matter right now.
This is the setup in the php.ini file. How should I set up SMTP? Are there any SMTP servers that require no verification or must I setup a server myself?
9 Answers 9
For example, I usually use PHPMailer with similar settings to this ones:
or, for more details, read on.
For Unix users, mail() is actually using Sendmail command to send email. Instead of modifying the application, you can change the environment. msmtp is an SMTP client with Sendmail compatible CLI syntax which means it can be used in place of Sendmail. It only requires a small change to your php.ini.
Then even the lowly mail() function can work with SMTP goodness. It is super useful if you’re trying to connect an existing application to mail services like sendgrid or mandrill without modifying the application.
Here is a way to do it with PHP PEAR
If you use Gmail SMTP remember to enable SMTP in your Gmail account, under settings
EDIT: If you can’t find Mail.php on debian/ubuntu you can install php-pear with
Then install the mail extention:
Then you should be able to load it by simply require_once «Mail.php» else it is located here: /usr/share/php/Mail.php
The problem is that PHP mail() function has a very limited functionality. There are several ways to send mail from PHP.
How can I send an email using PHP?
I am using PHP on a website and I want to add emailing functionality.
How do I send an email using PHP?
18 Answers 18
It’s possible using PHP’s mail() function. Remember the mail function will not work on a local server.
It allows you to use the mail function or use an smtp server transparently. It also handles HTML based emails and attachments so you don’t have to write your own implementation.
The class is stable and it is used by many other projects like Drupal, SugarCRM, Yii, and Joomla!
Here is an example from the page above:
If you are interested in html formatted email, make sure to pass Content-type: text/html; in the header. Example:
For more details, check php mail function.
Also look into the PEAR mail package Pear Mail Page
It seems to be a little more robust than the standard mail() function that is built in (if the standard function isn’t adequate).
Here is an excerpt from this page showing how it is used. PEAR Mail send() usage
For most projects, I use Swift mailer these days. It’s a very flexible and elegant object-oriented approach to sending emails, created by the same people who gave us the popular Symfony framework and Twig template engine.
Basic usage :
See the official documentation for more info on how to use Swift mailer.
For future readers: Try this if other answers don’t work (As was the case with me):
1.) Download PHPMailer, open the zip file and extract the folder to your project directory.
3.) Rename the extracted directory to PHPMailer and write the below code inside of your php script (the script must be outside of the PHPMailer folder)
this is very basic method to send plain text email using mail function.
The core way to send emails from PHP is to use its built in mail() function, but there are a couple of ready-to-use SDKs which can ease the integration:
P.S. I am employed with Pepipost.
The native PHP function mail() does not work for me. It issues the message:
503 This mail server requires authentication when attempting to send to a non-local e-mail address
So, I usually use PHPMailer package
I’ve downloaded the version 5.2.23 from: GitHub.
I’ve just picked 2 files and put them in my source PHP root
In PHP, the file needs to be added
After this, it’s just code:
It works like a charm
You can use a mail web service such as Postmark, Sendgrid etc.
Edit: I just use the Google Gmail API now. I had trouble sending reminder email to my employer’s organization due to strict filters. But Gmail works as long as you don’t spam people.
Sent the Email with this script
Once you press the Send email button, the email will be sent to Test@example.com
The above code is working for me.
Procedure for to send a user password via email using PHPMailer :
Step 1: First, Download PHPMailer Package from GitHub
You can just download the PHPMailer source files and include the required files manually.
You can download the ZIP file with the source code from the PHPMailer homepage[1], clicking on the “Clone or download” green button (on the right) and then selecting “Download ZIP”. Unzip the package inside the directory where you want to save the source files.
Step 2: Then, open (From Gmail Address) Google Account and do the following steps:
Step 3: Try to use below Code (Note: Here, I have provided only the functional code for to send a user password via email using PHP and MySQL)
Refer to these docs[1] for further information:
Авторизованная отправка почты с серверов виртуального хостинга
Как отправлять письма, используя PHP?
Скачать пример готового скрипта с функцией MailSmtp(): smtpauth.php.sample
Использовать описанную выше функцию MailSmtp() можно для прямой замены функции mail(), рассмотрим пример самой простой формы на PHP:
Для того, чтобы данная форма заработала без функции mail(), мы включили файл smtpauth.php через require_once и вызвали функцию MailSmtp(), описанную в нем, с аналогичными для mail() аргументами. При этом сам вызов mail() мы закомментировали в коде, чтобы избежать ошибки при выполнении скрипта.
Как отправлять письма, используя ASP.NET?
Если вы используете версию 2.0, то используя класс MailMessage (используется пространство имен System.Net.Mail), хорошо описанный здесь.
Ниже приведены примеры его использования для языков «C#» и «VisualBasic»:
Пример для языка «C#»:
Скачать пример готовой формы, демонстрирующей использование данного метода: MailForm.aspx.
Пример для языка «VisualBasic»:
Также существует устаревший (и не рекомендуется к использованию) класс SmtpMail (используется пространство имен System.Web.Mail). Ниже приведен пример его использования для языка «VisualBasic»:
Как отправлять письма, используя ASP?
Обратите внимание, что при использовании нашего smtp-сервера требуется авторизация, поэтому не забудьте добавить в скрипт соответствующие реквизиты доступа, например:
Некоторые CMS уже имеют встроенные средства для отправки корреспонденции или соответствующие модули, рассмотрим самые популярные из них.
WordPress
Для данной CMS существует специальный модуль «WP Mail SMTP», пример его конфигурации описан на странице модуля.
Обратите внимание на иллюстрацию в примере, в условиях нашей почтовой системы требуется использовать 25-й порт и SSL-шифрование не требуется.
Joomla
В панели администрирования перейдите в раздел «Общие настройки», выберете вкладку «Сервер». В поле «Почта» требуется выбрать способ отправки как « SMTP-сервер », в полях «Адрес SMTP-сервера » и « SMTP-логин » и « SMTP-пароль » укажите соответствующие реквизиты почтовой системы, например: smtp.masterhost.ru, ящик@ваш_домен и соответствующий пароль.
Подробнее вы можете прочитать в документации к данной CMS.
Drupal
NetCat
Отредактировать файл send_auth_mail.php из архива, указав в нём реквизиты подключения к нужному SMTP-серверу:
domain.tld следует заменить на имя вашего домена.
Предлагаемое решение работает со всеми модулями NetCat, которые используют стандартные функции данной CMS для отправки почты.
How to Send Emails in PHP?
We see numerous requests for guides on sending emails with some popular frameworks and libraries using an SMTP server, so we are launching a series of “how to” posts aimed at helping you painlessly configure the mail function in your application.
Today we are starting with PHP, one of the most popular web development languages.
PHP built-in mail function ()
There are two basic ways of sending emails with PHP: a built-in mail function and external mail packages.
PHP’s built-in mail function () is very simple, but it provides limited functionality for sending emails. You won’t be able to add attachments to your email, and building a beautiful HTML template with embedded images will be a tricky task as well.
The other side of the PHP mail function () is that the email is sent from your web server, which may cause issues with deliverability due to security concerns such as suspicion of spam and blacklisting. The best way to overcome this problem is sending messages via an SMTP server, however, this functionality is limited as well. PHP mail() does not usually allow you to use the external SMTP server and it does not support SMTP authentication.
Here’s what you can do with PHP’s built-in mail function():
It is suitable for simple, mostly text-based notifications in your local environment. If you need to communicate with your app’s users, it is better to install an external mailer package.
If you are still committed to the PHP built-in mail function() and are ready to accept the challenge, let’s take a look at the basic code and its main parameters.
Syntax and parameters
The PHP mail syntax is pretty simple:
It uses the following parameters:
Note that headers are optional, except for the “from” header: it must be specified, otherwise, you will receive an error message like Warning: mail(): “sendmail_from” not set in php.ini or custom “From:” header missing.
You can use additional headers to change the mail “From” address and set the “Reply to” address.
For more details and additional parameters, refer to the PHP documentation.
Sending HTML email using PHP mail() function
The body of the message can be written in HTML. However, as we’ve mentioned above, it should be simple. In the PHP mail function(), the HTML part will look like this:
It’s important to remember that to send HTML mail, you need to set the Content-type header:
Simple Transmission Protocol (SMTP)
Where do I specify the SMTP settings? This is a fair question. Go to the PHP installation folder and configure them in the “php.ini” file. But this will only work for localhost or Xmapp like solutions because as we have already mentioned, PHP mail function does not support SMTP authentication and doesn’t allow sending messages via external servers.
There are some other, rather haphazard options but we won’t promote them here. Alternatively, we recommend using external PHP mail packages for sending emails via an external SMTP server.
Sending multiple emails
To send your message to multiple recipients, specify their email addresses in “$to” = parameter separating them with comma(-s). It’s the only suitable method with a native mail() function. If you need to send a large volume of messages in a loop, try an external mailing package. In the official PHP documentation, PEAR::Mail is recommended.
PHP mailing packages
As we have already mentioned, the native PHP mail() function has limited functionality when it comes to mass sending. For example, it is not designed for creating engaging email templates that may boost your next campaign or sending a large volume of emails.
But since PHP is still one of the most popular programming languages, it also doesn’t lack resources for sending mass emails. Here are several plugins that we can highly recommend:
Pear Mail
Pear Mail is a class that provides multiple interfaces for sending emails (which is stated in their documentation).
Here is what you can do with Pear Mail:
Pear documentation looks a bit complicated but it’s still informative, and you can find several tutorials. To be able to compare several mail packages, let’s review code for sending a standard booking confirmation email. It will contain HTML and text parts, a single attachment, and will be sent via an authenticated SMTP server.
For email experiments, we will use Mailtrap, a fake SMTP server. It imitates a real SMTP server and traps your test email in the virtual inboxes. This way, your email samples will never go to the inboxes of the real customers.
Swift Mailer
Swift Mailer is another popular package for sending emails in PHP. It is feature-rich, well covered by documentation, and pretty straightforward in use.
Here is what you can do with Swift Mailer:
Besides that, Swift Mailer offers enhanced security and handles large attachments and images with low memory usage.
For more details, refer to the “How to Use Swift Mailer to Send Emails from PHP Apps” post. Below we will demonstrate a simple example of the same sending booking confirmation we used above.
PHPMailer
And finally, PHPMailer, which is the classic and the most popular email sending library for PHP. It deserves a separate article and a tutorial. You will find it here.
Here is what you can do with PHPMailer:
PHPMailer is protected against header injection attacks and automatically validates emails.
Now let’s send our booking confirmation with PHPMailer:
What else should you know about PHP mail sending options?
In this article, we have described the basic PHP email sending principles, syntax, and parameters. Moreover, we have reviewed the main ways of sending emails with PHP: its built-in mail function and the most popular external mail packages. PHPMailer and Swift Mailer are standard libraries for PHP email sending today, and PEAR Mail is still widely used.
Undoubtedly, external libraries offer much more advanced solutions, like SMTP authentication support and a wide set of HTML related features. However, PHP mail function() can still be an option if you are sending plain text notification via localhost.
Also, you can find several additional packages to supplement your mail tools:
Choose your option according to your current needs and preferences, and don’t forget to test emails before moving to production!