I am using cloudflare on my website and I want to keep my server's IP (the ORIGIN IP) private, to avoid DDoS attacks being sent directly to my server's IP. My server uses Apache, PHP, MySQL.
When using php mail to send emails (even if I use phpmailer library to send the emails through external SMTP) the IP of my server is added to the mail headers.
It happens with Google SMTP, Mailgun and others, because probably it is in their policy to write in the header the IP from which the mail came.
At the moment, the only solution that I have in mind and requires a lot of effort, which is to create my own REST API and send emails through another server, something like this:
ORIGIN SERVER IP sends email data in text format via my REST API to MY MAIL SERVER IP and then MY MAIL SERVER IP uses php mail function with phpmailer to send the email via SMTP to the user. This way, the IP of MY MAIL SERVER will appear in the email headers and not the IP of the ORIGIN SERVER.
Is there a much more elegant way to do this? Is there a mail service that offers a rest API and if I use their API, they won't display my server's IP in the email headers? Or maybe there is an already developed REST API / library for sending emails remotely as I requested, so I won't have to develop and test my own from scratch?
You should send emails through mailgun (or sendgrid, or jetmail, or SES, or ...) through their API and not the SMTP protocol and your IP won't be disclosed.
For instance for Mailgun SDK: https://github.com/mailgun/mailgun-php
$mg = Mailgun::create('key-example');
# Now, compose and send your message.
# $mg->messages()->send($domain, $params);
$mg->messages()->send('example.com', [
'from' => 'bob#example.com',
'to' => 'sally#example.com',
'subject' => 'The PHP SDK is awesome!',
'text' => 'It is so simple to send a message.'
]);
But there are SDK for most providers:
Sendgrid php sdk
Mailjet php sdk
AWS SES PHP SD
Moreover, I would recommend using SwiftMailer which is powerful library to handle email. One of the cool thing is that it abstract the transport and you would be able to switch from SMTP or any provider API using packages.
You can use e.g. mailchimp, amazon SES, or other mail service provider, they should not add your ip. But that services are paid.
Long time ago, at college, I can not use php mail command because of firewall rules so write my own SMTP autentication class.
Some time latter I start using PHPMailer class and I never had another problem, even using Gmail as sender.
Give a look at https://github.com/PHPMailer/PHPMailer .
This is a simple example:
<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
//Load composer's autoloader
require 'vendor/autoload.php';
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'user#example.com'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('from#example.com', 'Mailer');
$mail->addAddress('joe#example.net', 'Joe User'); // Add a recipient
$mail->addAddress('ellen#example.com'); // Name is optional
$mail->addReplyTo('info#example.com', 'Information');
$mail->addCC('cc#example.com');
$mail->addBCC('bcc#example.com');
//Attachments
$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
get an instance from any cloud provider, send REST request to that instance or whatever you prefer, then your original web server's ip will be totally invisible.
There is no API or elegant way to hide your IP from emails that you're sending. Any SMTP provider who offers this is worthy of blacklisting and would be immediately overcome by spammers signing up to abuse this privacy.
You must use your idea of creating an internal Web relay system to send to other IPs before initiating SMTP. But the hassle of setting that up should be more of a hassle than rebuilding your current site with another IP.
This sounds like a classic case of treating your server like a pet instead of like cattle. If rebuilding your current site on a new IP is less attractive than building and maintaining a custom Web API to hide your IP from exposure, you need to investigate automation tools.
Related
I have used the following PHP code to send email, but when I login to the gmail account after sending an email, the email that has sent is not recorded in the sent mail section of gmail. But emails are successfully delivered each time. I can use the IsSMTP() function in my laptop and in that case sent mails are recorded, but in GoDaddy VPS I can not use IsSMTP() but to use IsMail().
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\OAuth;
use PHPMailer\PHPMailer\POP3;
require '../PHPMailer/Exception.php';
require '../PHPMailer/PHPMailer.php';
require '../PHPMailer/SMTP.php';
require '../PHPMailer/OAuth.php';
require '../PHPMailer/POP3.php';
$mail = new PHPMailer(true);
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->IsMail();
//$mail->IsSMTP(); // if enabled instead of IsMail() an error "can not connect to SMTP" appears.
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'username#gmail.com';
$mail->Password = 'password';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
//Recipients
$mail->setFrom('username#gmail.com', 'OFFICE');
$mail->addReplyTo('username#gmail.com', 'OFFICE');
$mail->addBCC("username#gmail.com", "OFFICE");//since sent mails are not saved
$mail->isHTML(true);
$mail->addAddress('to#gmail.com');
$mail->Subject = 'Subject';
$mail->Body = 'Hello';
$mail->AltBody = 'Hello';
$mail->send();
The problem is that Godaddy (and many other VPS providers) block SMTP ports in order to fight spammers.
When you are using $mail->IsMail(), the e-mails will go via GoDaddy's servers completely bypassing your Gmail account.
Now there is another problem as well, Google protects your #gmail.com addresses using various methods (such as SPF), so even if you are able to send the e-mail, it will be most likely marked as SPAM - if delivered at all. Otherwise anyone could send e-mails as you..
I'd highly suggest purchasing a domain (if you dont have one already) and either:
Hosting it in GoDaddys e-mail service and sending it via their SMTP servers (their SMTP servers are allowed)
Use external service which does not rely on SMTP (such as MailGun and their PHP SDK for example, but do your own research for a suitable one)
There might be some other "hacky" ways to still send these e-mails trough Gmail if you really need to, such as using VPN inside VPS or[1] proxying google SMTP externally on some other port which is not blocked. Beware, these methods still require some external service (most likely paid) and might conflict with GoDaddy's and/or Gmail TOS
[1] Apparently most of the VPN providers also block SMTP ports to avoid e-mail spammer flood
How can i use proxies to send smtp mails using PHPmailer?
The proxy format is: proxy/port/user/password
I am using following code to send email:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require 'C:/xampp/php/pear/PHPMailer-master/src/PHPMailer.php';
require 'C:/xampp/php/pear/PHPMailer-master/src/SMTP.php';
$mail = new PHPMailer(true);
$mail->SMTPDebug = 3;
$mail->isSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->Username = "test#gmail.com";
$mail->Password = "password";
$mail->SMTPSecure = "tls";
$mail->Port = 587;
$mail->From = "test#gmail.com";
$mail->FromName = "Name";
$mail->addAddress("address#yahoo.com", "name");
$mail->isHTML(true);
$mail->Subject = "Mail Subject";
$mail->Body = "Something";
$mail->AltBody = "This is the plain text version of the email content";
try {
$mail->send();
echo "Message has been sent successfully";
} catch (Exception $e) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
?>
I tried with socat had no success since socat cannot be installed on my server,i also tried with curl but had no success.
I'm also aware that phpmailer has no explicit SMTP proxy support.
Also guide me if there is a substitute for PHPMailer that can use proxy, in case proxies can't be configured for PHPMailer.
I suspect this is the same question as was asked on GitHub recently.
The short answer is that you can't. Not because PHPMailer doesn't support it, but because proxying SMTP doesn't really exist in any practical sense because of its disconnected, async, store-and-forward nature. It's completely unlike HTTP in this respect. You have two alternatives:
Use a TCP proxy. You specify the proxy host IP as your mail server, and it forwards the traffic. This is completely transparent to PHPMailer, and so does not require any specific support, but you are likely to run into TLS issues.
Use an SMTP relay. Send to a "nearby" mail server (usually referred to as a "smarthost") which then deals with onward delivery for you. This is probably what you want. Again, PHPMailer doesn't care about your relaying arrangements here as you simply deliver to the smarthost as usual, so no specific support is required.
The reason an "SMTP proxy" can't really work is because there is no guarantee that an SMTP server can make an onward delivery. It may require literally days of waiting and retrying to deliver a message, and this means that the proxy needs to implement everything an SMTP server does, turning it into an SMTP relay.
There are SMTP proxies, but they are typically only ever used in high-availability environments, such as in SMTP front-end load balancers, where immediate onward delivery is essentially guaranteed to be possible, so the proxy needs no local storage or queuing abilities. That's probably not what you're looking for.
If you want more than that you need to say exactly what it is you're trying to achieve, why, and how.
$from = "someonelse#example.com";
$headers = "From:" . $from;
echo mail ("borutflis1#gmail.com" ,"testmailfunction" , "Oj",$headers);
I have trouble sending email in PHP. I get an error: SMTP server response: 530 SMTP authentication is required.
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.
[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP = localhost
; http://php.net/smtp-port
smtp_port = 25
; For Win32 only.
; http://php.net/sendmail-from
sendmail_from = someonelse#example.com
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?
When you are sending an e-mail through a server that requires SMTP Auth, you really need to specify it, and set the host, username and password (and maybe the port if it is not the default one - 25).
For example, I usually use PHPMailer with similar settings to this ones:
$mail = new PHPMailer();
// Settings
$mail->IsSMTP();
$mail->CharSet = 'UTF-8';
$mail->Host = "mail.example.com"; // SMTP server example
$mail->SMTPDebug = 0; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Port = 25; // set the SMTP port for the GMAIL server
$mail->Username = "username"; // SMTP account username example
$mail->Password = "password"; // SMTP account password example
// Content
$mail->setFrom('domain#example.com');
$mail->addAddress('receipt#domain.com');
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
You can find more about PHPMailer here: https://github.com/PHPMailer/PHPMailer
<?php
ini_set("SMTP", "aspmx.l.google.com");
ini_set("sendmail_from", "YOURMAIL#gmail.com");
$message = "The mail message was sent with the following mail setting:\r\nSMTP = aspmx.l.google.com\r\nsmtp_port = 25\r\nsendmail_from = YourMail#address.com";
$headers = "From: YOURMAIL#gmail.com";
mail("Sending#provider.com", "Testing", $message, $headers);
echo "Check your email now....<BR/>";
?>
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.
sendmail_path = "/usr/bin/msmtp -C /path/to/your/config -t"
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.
The problem is that PHP mail() function has a very limited functionality. There are several ways to send mail from PHP.
mail() uses SMTP server on your system. There are at least two servers you can use on Windows: hMailServer and xmail. I spent several hours configuring and getting them up. First one is simpler in my opinion. Right now, hMailServer is working on Windows 7 x64.
mail() uses SMTP server on remote or virtual machine with Linux. Of course, real mail service like Gmail doesn't allow direct connection without any credentials or keys. You can set up virtual machine or use one located in your LAN. Most linux distros have mail server out of the box. Configure it and have fun. I use default exim4 on Debian 7 that listens its LAN interface.
Mailing libraries use direct connections. Libs are easier to set up. I used SwiftMailer and it perfectly sends mail from Gmail account. I think that PHPMailer is pretty good too.
No matter what choice is your, I recommend you use some abstraction layer. You can use PHP library on your development machine running Windows and simply mail() function on production machine with Linux. Abstraction layer allows you to interchange mail drivers depending on system which your application is running on. Create abstract MyMailer class or interface with abstract send() method. Inherit two classes MyPhpMailer and MySwiftMailer. Implement send() method in appropriate ways.
There are some SMTP servers that work without authentication, but if the server requires authentication, there is no way to circumvent that.
PHP's built-in mail functions are very limited - specifying the SMTP server is possible in WIndows only. On *nix, mail() will use the OS's binaries.
If you want to send E-Mail to an arbitrary SMTP server on the net, consider using a library like SwiftMailer. That will enable you to use, for example, Google Mail's outgoing servers.
In cases where you are hosting a WordPress site on Linux and have server access, you can save some headaches by installing msmtp which allows you to send via SMTP from the standard PHP mail() function. msmtp is a simpler alternative to postfix which requires a bit more configuration.
Here are the steps:
Install msmtp
sudo apt-get install msmtp-mta ca-certificates
Create a new configuration file:
sudo nano /etc/msmtprc
...with the following configuration information:
# Set defaults.
defaults
# Enable or disable TLS/SSL encryption.
tls on
tls_starttls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
# Set up a default account's settings.
account default
host <smtp.example.net>
port 587
auth on
user <username#example.net>
password <password>
from <address-to-receive-bounces#example.net>
syslog LOG_MAIL
You need to replace the configuration data represented by everything within "<" and ">" (inclusive, remove these). For host/username/password, use your normal credentials for sending mail through your mail provider.
Tell PHP to use it
sudo nano /etc/php5/apache2/php.ini
Add this single line:
sendmail_path = /usr/bin/msmtp -t
Complete documentation can be found here:
https://marlam.de/msmtp/
I know this is an old question but it's still active and all the answers I saw showed basic authentication, which is deprecated. Here is an example showing how to send via Google's Gmail servers using PHPMailer with XOAUTH2 authentication:
//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\OAuth;
//Alias the League Google OAuth2 provider class
use League\OAuth2\Client\Provider\Google;
//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
date_default_timezone_set('Etc/UTC');
//Load dependencies from composer
//If this causes an error, run 'composer install'
require '../vendor/autoload.php';
//Create a new PHPMailer instance
$mail = new PHPMailer();
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
//SMTP::DEBUG_OFF = off (for production use)
//SMTP::DEBUG_CLIENT = client messages
//SMTP::DEBUG_SERVER = client and server messages
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
//Set the SMTP port number:
// - 465 for SMTP with implicit TLS, a.k.a. RFC8314 SMTPS or
// - 587 for SMTP+STARTTLS
$mail->Port = 465;
//Set the encryption mechanism to use:
// - SMTPS (implicit TLS on port 465) or
// - STARTTLS (explicit TLS on port 587)
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Set AuthType to use XOAUTH2
$mail->AuthType = 'XOAUTH2';
//Fill in authentication details here
//Either the gmail account owner, or the user that gave consent
$email = 'someone#gmail.com';
$clientId = 'RANDOMCHARS-----duv1n2.apps.googleusercontent.com';
$clientSecret = 'RANDOMCHARS-----lGyjPcRtvP';
//Obtained by configuring and running get_oauth_token.php
//after setting up an app in Google Developer Console.
$refreshToken = 'RANDOMCHARS-----DWxgOvPT003r-yFUV49TQYag7_Aod7y0';
//Create a new OAuth2 provider instance
$provider = new Google(
[
'clientId' => $clientId,
'clientSecret' => $clientSecret,
]
);
//Pass the OAuth provider instance to PHPMailer
$mail->setOAuth(
new OAuth(
[
'provider' => $provider,
'clientId' => $clientId,
'clientSecret' => $clientSecret,
'refreshToken' => $refreshToken,
'userName' => $email,
]
)
);
//Set who the message is to be sent from
//For gmail, this generally needs to be the same as the user you logged in as
$mail->setFrom($email, 'First Last');
//Set who the message is to be sent to
$mail->addAddress('someone#gmail.com', 'John Doe');
//Set the subject line
$mail->Subject = 'PHPMailer GMail XOAUTH2 SMTP test';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->CharSet = PHPMailer::CHARSET_UTF8;
$mail->msgHTML(file_get_contents('contentsutf8.html'), __DIR__);
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
$mail->addAttachment('images/phpmailer_mini.png');
//send the message, check for errors
if (!$mail->send()) {
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message sent!';
}
Reference: PHPMailer examples folder
For another approach, you can take a file like this:
From: Sunday <sunday#gmail.com>
To: Monday <monday#gmail.com>
Subject: Day
Tuesday Wednesday
and send like this:
<?php
$a1 = ['monday#gmail.com'];
$r1 = fopen('a.txt', 'r');
$r2 = curl_init('smtps://smtp.gmail.com');
curl_setopt($r2, CURLOPT_MAIL_RCPT, $a1);
curl_setopt($r2, CURLOPT_NETRC, true);
curl_setopt($r2, CURLOPT_READDATA, $r1);
curl_setopt($r2, CURLOPT_UPLOAD, true);
curl_exec($r2);
https://php.net/function.curl-setopt
I created a simple lightweight SMTP email sender for PHP if anybody needs it. Here is the URL:
https://github.com/Nerdtrix/EZMAIL
It was tested in both environments, production and development.
So I'm trying to send an email using current version of PHPMailer (https://github.com/PHPMailer/PHPMailer). The SMTP connection and the mail sending is working fine, except the script is not using the "SetFrom" $email variable for the senders mail, but instead the "Username" email.
I've tried using multiple forms of setting the "From" mail and nothing seems to work, although it's important to note that the "name" in the "SetForm" is set just fine, but "email" is not.
Here's the code:
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'USERNAME(MY EMAIL)';
$mail->Password = 'PASSWORD';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->isHTML(true);
$mail->SetFrom($email,$name);
$mail->addAddress($email_received);
$mail->Subject = $subject;
$mail->Body = $user_msg;
This is a common question, asked many times on here. gmail does not allow you to set arbitrary senders - if you're sending through gmail, you have to use either your gmail address, or a pre-configured alternative. See here for google's docs on the matter. Generally it's a bad idea to try to do this anyway as it's likely to cause your message to fail SPF tests that the address owner may have configured.
If you check header of the received mail, you will find your SetFrom email id defined as X-Google-Original-From.
It's because Gmail automatically rewrites the From line of any email you send via its SMTP server to the default 'Send mail as` email address in your Gmail or Google Apps email account Settings.
If you really want to use Gmail as the email provider, then you need to open a Google Apps account and verify that you own the domain which you are using for your email id.
There is also a workaround for this problem (but not recommended):
In your Gmail Settings, go to the 'Accounts' tab and add another email address you own in Send mail as section. This will cause Google's SMTP server to re-write the From field with whatever address you enabled as the default Send mail as address. Here, you need to enter smtp settings of your domain.
So, when you send email using this setting, PHPMailer will connect to Gmail and Gmail will connect to your SMTP server before sending any email.
$from = "someonelse#example.com";
$headers = "From:" . $from;
echo mail ("borutflis1#gmail.com" ,"testmailfunction" , "Oj",$headers);
I have trouble sending email in PHP. I get an error: SMTP server response: 530 SMTP authentication is required.
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.
[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP = localhost
; http://php.net/smtp-port
smtp_port = 25
; For Win32 only.
; http://php.net/sendmail-from
sendmail_from = someonelse#example.com
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?
When you are sending an e-mail through a server that requires SMTP Auth, you really need to specify it, and set the host, username and password (and maybe the port if it is not the default one - 25).
For example, I usually use PHPMailer with similar settings to this ones:
$mail = new PHPMailer();
// Settings
$mail->IsSMTP();
$mail->CharSet = 'UTF-8';
$mail->Host = "mail.example.com"; // SMTP server example
$mail->SMTPDebug = 0; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Port = 25; // set the SMTP port for the GMAIL server
$mail->Username = "username"; // SMTP account username example
$mail->Password = "password"; // SMTP account password example
// Content
$mail->setFrom('domain#example.com');
$mail->addAddress('receipt#domain.com');
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
You can find more about PHPMailer here: https://github.com/PHPMailer/PHPMailer
<?php
ini_set("SMTP", "aspmx.l.google.com");
ini_set("sendmail_from", "YOURMAIL#gmail.com");
$message = "The mail message was sent with the following mail setting:\r\nSMTP = aspmx.l.google.com\r\nsmtp_port = 25\r\nsendmail_from = YourMail#address.com";
$headers = "From: YOURMAIL#gmail.com";
mail("Sending#provider.com", "Testing", $message, $headers);
echo "Check your email now....<BR/>";
?>
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.
sendmail_path = "/usr/bin/msmtp -C /path/to/your/config -t"
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.
The problem is that PHP mail() function has a very limited functionality. There are several ways to send mail from PHP.
mail() uses SMTP server on your system. There are at least two servers you can use on Windows: hMailServer and xmail. I spent several hours configuring and getting them up. First one is simpler in my opinion. Right now, hMailServer is working on Windows 7 x64.
mail() uses SMTP server on remote or virtual machine with Linux. Of course, real mail service like Gmail doesn't allow direct connection without any credentials or keys. You can set up virtual machine or use one located in your LAN. Most linux distros have mail server out of the box. Configure it and have fun. I use default exim4 on Debian 7 that listens its LAN interface.
Mailing libraries use direct connections. Libs are easier to set up. I used SwiftMailer and it perfectly sends mail from Gmail account. I think that PHPMailer is pretty good too.
No matter what choice is your, I recommend you use some abstraction layer. You can use PHP library on your development machine running Windows and simply mail() function on production machine with Linux. Abstraction layer allows you to interchange mail drivers depending on system which your application is running on. Create abstract MyMailer class or interface with abstract send() method. Inherit two classes MyPhpMailer and MySwiftMailer. Implement send() method in appropriate ways.
There are some SMTP servers that work without authentication, but if the server requires authentication, there is no way to circumvent that.
PHP's built-in mail functions are very limited - specifying the SMTP server is possible in WIndows only. On *nix, mail() will use the OS's binaries.
If you want to send E-Mail to an arbitrary SMTP server on the net, consider using a library like SwiftMailer. That will enable you to use, for example, Google Mail's outgoing servers.
In cases where you are hosting a WordPress site on Linux and have server access, you can save some headaches by installing msmtp which allows you to send via SMTP from the standard PHP mail() function. msmtp is a simpler alternative to postfix which requires a bit more configuration.
Here are the steps:
Install msmtp
sudo apt-get install msmtp-mta ca-certificates
Create a new configuration file:
sudo nano /etc/msmtprc
...with the following configuration information:
# Set defaults.
defaults
# Enable or disable TLS/SSL encryption.
tls on
tls_starttls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
# Set up a default account's settings.
account default
host <smtp.example.net>
port 587
auth on
user <username#example.net>
password <password>
from <address-to-receive-bounces#example.net>
syslog LOG_MAIL
You need to replace the configuration data represented by everything within "<" and ">" (inclusive, remove these). For host/username/password, use your normal credentials for sending mail through your mail provider.
Tell PHP to use it
sudo nano /etc/php5/apache2/php.ini
Add this single line:
sendmail_path = /usr/bin/msmtp -t
Complete documentation can be found here:
https://marlam.de/msmtp/
I know this is an old question but it's still active and all the answers I saw showed basic authentication, which is deprecated. Here is an example showing how to send via Google's Gmail servers using PHPMailer with XOAUTH2 authentication:
//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\OAuth;
//Alias the League Google OAuth2 provider class
use League\OAuth2\Client\Provider\Google;
//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
date_default_timezone_set('Etc/UTC');
//Load dependencies from composer
//If this causes an error, run 'composer install'
require '../vendor/autoload.php';
//Create a new PHPMailer instance
$mail = new PHPMailer();
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
//SMTP::DEBUG_OFF = off (for production use)
//SMTP::DEBUG_CLIENT = client messages
//SMTP::DEBUG_SERVER = client and server messages
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
//Set the SMTP port number:
// - 465 for SMTP with implicit TLS, a.k.a. RFC8314 SMTPS or
// - 587 for SMTP+STARTTLS
$mail->Port = 465;
//Set the encryption mechanism to use:
// - SMTPS (implicit TLS on port 465) or
// - STARTTLS (explicit TLS on port 587)
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Set AuthType to use XOAUTH2
$mail->AuthType = 'XOAUTH2';
//Fill in authentication details here
//Either the gmail account owner, or the user that gave consent
$email = 'someone#gmail.com';
$clientId = 'RANDOMCHARS-----duv1n2.apps.googleusercontent.com';
$clientSecret = 'RANDOMCHARS-----lGyjPcRtvP';
//Obtained by configuring and running get_oauth_token.php
//after setting up an app in Google Developer Console.
$refreshToken = 'RANDOMCHARS-----DWxgOvPT003r-yFUV49TQYag7_Aod7y0';
//Create a new OAuth2 provider instance
$provider = new Google(
[
'clientId' => $clientId,
'clientSecret' => $clientSecret,
]
);
//Pass the OAuth provider instance to PHPMailer
$mail->setOAuth(
new OAuth(
[
'provider' => $provider,
'clientId' => $clientId,
'clientSecret' => $clientSecret,
'refreshToken' => $refreshToken,
'userName' => $email,
]
)
);
//Set who the message is to be sent from
//For gmail, this generally needs to be the same as the user you logged in as
$mail->setFrom($email, 'First Last');
//Set who the message is to be sent to
$mail->addAddress('someone#gmail.com', 'John Doe');
//Set the subject line
$mail->Subject = 'PHPMailer GMail XOAUTH2 SMTP test';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->CharSet = PHPMailer::CHARSET_UTF8;
$mail->msgHTML(file_get_contents('contentsutf8.html'), __DIR__);
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
$mail->addAttachment('images/phpmailer_mini.png');
//send the message, check for errors
if (!$mail->send()) {
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message sent!';
}
Reference: PHPMailer examples folder
For another approach, you can take a file like this:
From: Sunday <sunday#gmail.com>
To: Monday <monday#gmail.com>
Subject: Day
Tuesday Wednesday
and send like this:
<?php
$a1 = ['monday#gmail.com'];
$r1 = fopen('a.txt', 'r');
$r2 = curl_init('smtps://smtp.gmail.com');
curl_setopt($r2, CURLOPT_MAIL_RCPT, $a1);
curl_setopt($r2, CURLOPT_NETRC, true);
curl_setopt($r2, CURLOPT_READDATA, $r1);
curl_setopt($r2, CURLOPT_UPLOAD, true);
curl_exec($r2);
https://php.net/function.curl-setopt
I created a simple lightweight SMTP email sender for PHP if anybody needs it. Here is the URL:
https://github.com/Nerdtrix/EZMAIL
It was tested in both environments, production and development.