php mail() function not working to send an email [duplicate] - php

I have installed wamp on windows 8.
Got error:
Warning: mail() [function.mail]: Failed to connect to mailserver at
"localhost" port 25, verify your "SMTP" and "smtp_port" setting in
php.ini or use ini_set() in C:\wamp\www\mail.php on line 9
Here is the simple source code:
<?php
// The message
$message = "Line 1\r\nLine 2\r\nLine 3";
// In case any of our lines are larger than 70 characters, we should use wordwrap()
$message = wordwrap($message, 70, "\r\n");
// Send
mail('caffeinated#example.com', 'My Subject', $message);
?>
Which software do i have to install to email through php on windows 8? sendmail, msmtp or ssmtp?

Try this
Configure This Setups
in php.ini
SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = my-gmail-id#gmail.com
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"
in sendmail.ini:
smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
auth_username=my-gmail-id#gmail.com
auth_password=my-gmail-password
force_sender=my-gmail-id#gmail.com
Important: comment following line if there is another sendmail_path in the php.ini : sendmail_path="C:\xampp\mailtodisk\mailtodisk.exe"
Note: Tested and works fine in my Windows 8.1

Possible solution. See this question
For me configuring a mail client on localhost is quite difficult. I also tried quite a few times. Later I moved on to other solutions.
You can use SwiftMailer or PhpMailer with some configuration or you can try this tool with zero configuration.

On a side note, if you are using your windows PC for development and not as a production server, then I suggest that you don't bother setting up a sendmail in windows, just use this handy tool.
Test Mail Server Tool (Its Free)
It will emulate an email server and once any script tries to send an email, it will intercept it and open it for you as an .eml file, which you can open up in any email reader like outlook or mail viewer(again its free).
Now setting this tool up is just a breez, and you will thank me later for all the time that you saved, from not having to manually setup the sendmail, which I must mention is meant to be on a linux machine. ;)

I'd recommend mercury (http://www.pmail.com/downloads_s3_t.htm - Mercury/32 Mail Transport System for Win32 and NetWare Systems v4.74).
This is included in XAMPP, fairly easy to set up and you don't need to configure or (ab)use an email account. You can see the whole smtp transaction in mercury mail log window.

Look here for an excellent answer on how to setup mailing from php: PHP mail form doesn't complete sending e-mail

Use this function tool:
https://github.com/PHPMailer/PHPMailer
Mail() is prette dificult to use and this function allows you to use the email servers STMP function to send emails.
Read documentation here:
https://github.com/PHPMailer/PHPMailer/blob/master/README.md

You need to use email server along with php.
https://www.hmailserver.com/

When you are using an e-mail sender functionality through a server that requires SMTP
Authentication, you must 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:
//ini settings
ini_set("SMTP", "aspmx.l.google.com");
ini_set("sendmail_from", "YOURMAIL#gmail.com");
$mail = new PHPMailer();
$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"; //Your SMTP account username example
$mail->Password = "password"; //Your SMTP account password example
You can find more about PHPMailer here.
You can video ride for how SMTP configure on wondows here.

Related

SMTP Not Working on WAMP Server

I have installed WAMP Server on my Windows 10 PC and when I try to send emails through a valid SMTP configuration it doesn't work. The same SMTP configuration works on another LAMP installation and also on a live server.
When I try sending the email through a PrestaShop installation I get following error:
Error: Please check your configuration
Connection could not be established with host smtp.gmail.com [ #0]
And with Magento I get following error:
SMTP Pro Self Test Results
Sending test email to your contact form address: xxxxxxx#example.com from: xxx.adsxx#example.com. Unable to send test email.
Exception message was: Could not open socket
Please check the user guide for frequent error messages and their solutions.
Default templates exist.
Email communications are enabled.
As per my understanding, this issue is not dependent on Magento or PrestaShop, it is coming because of the WAMP installation.
Do I have to enable some extension or something for the WAMP installation? Or have I missed something else?
Please help. Already wasted a lot of time investigating and trying solutions from the Web, but nothing seems to be working.
Download the sendmail.zip
Create a folder named “sendmail” in “C:\wamp\”.
Extract these 4 files in “sendmail” folder: “sendmail.exe”, “libeay32.dll”, “ssleay32.dll” and “sendmail.ini”.
Open the “sendmail.ini” file and configure it as following
smtp_server=smtp.gmail.com
smtp_port=465
smtp_ssl=ssl
default_domain=localhost
error_logfile=error.log
debug_logfile=debug.log
auth_username=[your_gmail_account_username]#gmail.com
auth_password=[your_gmail_account_password]
pop3_server=
pop3_username=
pop3_password=
force_sender=
force_recipient=
hostname=localhost
You do not need to specify any value for these properties: pop3_server, pop3_username, pop3_password, force_sender, force_recipient. The error_logfile and debug_logfile settings should be kept blank if you have already sent successful email(s) otherwise size of this file will keep increasing. Enable these log file settings if you don’t get able to send email using sendmail.
Enable IMAP Access in your GMail’s Settings -> Forwarding and POP/IMAP -> IMAP Access:
Enable “php_openssl” and “php_sockets” extensions for PHP compiler:
Open php.ini from “C:\wamp\bin\apache\Apache2.2.17\bin” and configure it as following (The php.ini at “C:\wamp\bin\php\php5.3.x” would not work) (You just need to configure the last line in the following code, prefix semicolon (;) against other lines):
Restart WAMP Server.
Create a PHP file and write the following code in it:
<?php
$to = 'recipient#yahoo.com';
$subject = 'Testing sendmail.exe';
$message = 'Hi, you just received an email using sendmail!';
$headers = 'From: [your_gmail_account_username]#gmail.com' . "\r\n" .
'MIME-Version: 1.0' . "\r\n" .
'Content-type: text/html; charset=utf-8';
if(mail($to, $subject, $message, $headers))
echo "Email sent";
else
echo "Email sending failed";
?>
Make appropriate changes in $to and $headers variables to set recipient and sender (“From” header) addresses. Save it as “send-mail.php”. (You can save it anywhere or inside any sub-folder in “C:\wamp\www”.)
Open this file in browser, it MUST work now
These are possibly causes which prevent you from sending mails via WAMP server.
Your firewall configurations may (by default) block some ports used by WAMP for sending emails.
These ports may be already used by your others applications. Prefer to this to know which port is being used by which application.
Administrators rights are required for the WAMP server to be able to send mail. Run the server as administrator.
Since you're sure that settings have already worked on a server so I assume there nothing to check with PHP.ini
make sure that your -
extension=php_openssl.dll
extension=php_sockets.dll
is enable in php.ini file.
check is Enable ssl_module under Apache Module.
You can use PHP Mailer or Download php mailer with example from here. Once you setup the phpmailer with your project use following code to send mail using gmail SMTP :
require_once('inc/class.phpmailer.php'); # INCLUDE PHPMailer CLASS FILE
require_once("inc/class.smtp.php"); # INCLUDE OTHER SMTP FILE
Include above files in your project or PHP file which you use to send email and then :
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0; # ENABLE SMTP DEBUG INFORMATION (FOR TESTING)
# 1 = ERROR AND MESSAGE
# 2 = MESSAGE ONLY
$mail->SMTPAuth = true; # ENABLE SMTP AUTHENTICATION
$mail->Host = "Host Addresss"; # smtp.gmail.com
$mail->Port = 587; # PORT NUMBER
$mail->Username = "example#gmail.com"; # SMTP EMAIL USER NAME
$mail->Password = "xxxxxxx"; # SMTP ACCOUNT PASSWORD
$mail->SetFrom('example#gmail.com', 'Test Name');
$mail->SMTPSecure = 'tls';
$mail->AddReplyTo("example#gmail.com","SMTP TEST");
$v_Msg ="This is a test message via SMTP";
$mail->Subject = "EMAIL SUBJECT";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; # OPTIONAL
$address = "sendto#email.com"; # ADDRESS WHERE YOU WANT TO SEND MAIL
$mail->AddAddress($address, "TESTING");
$mail->MsgHTML($v_Msg); # EMAIL CONTENT
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo; # ERROR MESSAGE, IF MAIL NOT SENT SUCCESSFULLY
}else {
echo "Message sent!"; # SUCCESS MESSAGE
}
NOTE : Make sure your smtp gmail account must be Allow less secure apps: ON. You can turn on less secure apps for your gmail
account using THIS URL
Sometimes its easier not to rely on your own smtp server. (firewalls everywhere)
You can experiment with some other online mail delivery services than gmail, like mailgun or sendgrid.

Send mail with php and gmail smtp? [duplicate]

$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.

phpmailer ERROR :Could not instantiate mail function

I am using localhost WAMP server (Windows) for webhosting. I am getting the following error.
phpmailer ERROR :Could not instantiate mail function.
I have tried many solutions but nothing worked for me.
PHP mailing script
$mailer = new PHPMailer();
$mailer->IsMAIL();
$mailer->CharSet = 'utf-8';
$mailer->AddAddress($formvars['email'],$formvars['name']);
$mailer->Subject = "Your registration with ".$this->sitename;
$mailer->From = $this->GetFromAddress();
$confirmcode = $formvars['confirmcode'];
$confirm_url = $this->GetAbsoluteURLFolder().'/confirmreg.php?code='.$confirmcode;
$mailer->Body ="Hello ".$formvars['name']."\r\n\r\n".
"Thanks for your registration with ".$this->sitename."\r\n".
"Please click the link below to confirm your registration.\r\n".
"$confirm_url\r\n".
"\r\n".
"Regards,\r\n".
"Webmaster\r\n".
$this->sitename;
if(!$mailer->Send())
{
$this->HandleError("Failed sending registration confirmation email.".$mailer->ErrorInfo);
//echo "Mailer Error: " . $mailer->ErrorInfo;
return false;
}
return true;
How do I diagnose this error?
$mailer->IsMAIL(); tells PHPMailer to use the PHP mail() function for emails delivery. It works out of the box on Unix-like OSes but not on Windows because the desktop versions of Windows do not install a SMTP server (it is available on the installation disc).
In order to make it work on Windows you have to change the PHP configuration. Either you edit php.ini (the configuration will apply globally) or you can use function ini_set() to change it only for current execution of the current script.
The best way is to change php.ini. You can find it in the PHP's installation directory or in the Windows's directory. Check the output of PHP function phpinfo() to find out its exact location.
Open php.ini in a text editor (the one you use to write the code is the best) and search for a section that looks like this:
[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 = me#example.com
For SMTP, use the name or the IP address of your company's mail server. Or your ISP's mail server if you are at home. Or check the configuration of your email client.
The smtp_port is either 25 for standard SMTP or 587 if the server uses SSL to encrypt its communication.
Also uncomment the sendmail_from setting if it is commented out (remove the ; from the beginning of line) and put your email address there.
Read more about the PHP configuration for sending emails on Windows on the documentation page.
Another option is to install a SMTP server on the computer. You can find one on the Windows installation disc or you can use a third-party solution.
If you choose to not install a SMTP server on the computer you don't even need to modify php.ini. You can change the code of the script to use a SMTP server:
$mailer = new PHPMailer();
$mailer->IsSMTP();
$mailer->Host = "mail.example.com";
$mailer->Port = 25;
Check this PHPmailer example for all the settings and their meaning.
If the SMTP server uses SMTP authentication (the webmail providers do it, your ISP or your company might do it or might not do it) then you have to also add:
$mail->SMTPAuth = true;
$mail->Username = "yourname#example.com";
$mail->Password = "yourpassword";
If you use Gmail's SMTP server, for example, then use your Gmail email address and password. Replace "Gmail" with "Hotmail" or "Yahoo!" or your webmail provider or your company in the sentence above.
Configuring a working mail client from localhost is always a mission and often "unecessary" considering it's just a sandbox. Although some developers want to solve the puzzle (I am one of those), some look for an easier alternative.
I would suggest that you install HMailServer
I have seen lots of people having great luck at a very fast speed using hmail.
Check this post for the step by step: How to send email from localhost WAMP Server to send email Gmail Hotmail or so forth?

Sending email with PHP from an SMTP server

$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.

Help with PHP mail() function [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
php mail() function on localhost
I'm trying to do some localhost testing for password recovery on my site, but when I try to send an email, I get the following error:
Warning: mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()
Here are the relevant settings in my php.ini file.
; 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 = you#yourdomain
I am not sure what to set these to for localhost testing. I realize that I need to set SMTP to whatever my provider's mail server is, but I work in a shared office building so I don't know how to even find out who provides the internet here.
Thanks in advance.
PHP's mail() function doesn't implement SMTP protocol directly. Instead it relies on sendmail() MTA (SMTP server), or a replacement like postfix or mstmp.
It works fine on Unix as long as MTA installed.
On Windows (from PHP.net manual):
The Windows implementation of mail() differs in many ways from the
Unix implementation. First, it doesn't use a local binary for
composing messages but only operates on direct sockets which means a
MTA is needed listening on a network socket (which can either on the
localhost or a remote machine).
So - the moral of the story - you need to install mail server.
However - if it's for test purpose only - simply get a PHP library that actually implements SMTP protocol and use your regular gmail email address to send emails:
Instead of using PHP's mail() use one of these:
PHPmailer
SwiftMailer
Zend\Mail
These PHP libraries actually implement SMTP protocol so one can easily send emails from any platform, without email server installed on the same machine:
PHPMAILER example:
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "stmp.gmail.com"; // SMTP server
$mail->SMTPDebug = 1; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "ssl"; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->Username = "some_email#gmail.com"; // GMAIL username
$mail->Password = "pass111"; // GMAIL password
$mail->SetFrom('some_email#gmail.com', 'My name is slim shady');
$mail->AddReplyTo("some_email#gmail.com","My name is slim shady");
$mail->Subject = "Hey, check out http://www.site.com";
$mail->AltBody = "Hey, check out this new post on www.site.com"; // optional, comment out and test
$mail->MsgHTML($body);
$address = "some_email#gmail.com";
$mail->AddAddress($address, "My name is slim shady");
PHP's mail requires a local mailserver to run.
Edit: As the PHP documentation site for mail() reveils, you may use a Mail package from PEAR.
For testing purposes, I'd recommend setting up a fake mail server like Dumbster.
http://quintanasoft.com/dumbster/

Categories