This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 6 years ago.
I want to use the PHP mail function to send a HTML form to my mail.
When I run the code it no error occurs, but I don't receive an email.
I used the following code:
<?php
$to = 'email#email.com';
$subject = 'Subject';
$message = 'Message here';
$headers = 'From: email#email.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
?>
I'm hosting my web app on Microsoft Azure with PHP 7.0.
I assume Microsoft turned PHP mail off. (many hosting providers do)
Microsoft says that you should use SendGrid. You can read the full tutorial here: https://azure.microsoft.com/en-us/documentation/articles/store-sendgrid-php-how-to-send-email/
I've tried to use the php mail() function but I can't get it working so I've searched for some answers and this works:
https://github.com/PHPMailer/PHPMailer
You can use it when you will send a mail to a gmail account or for local email servers.
Notes:
Make sure your path for PHPMailerAutoload.php is correct when you are requiring. For example:
require 'assets/api/PHPMailer-master/PHPMailerAutoload.php';
You must know the host name if you are going to send to a local email server.
You must have an account that you can use to send a mail.
Analyze how the code works and feel free to comment for further questions.
I'll attach a sample code here from a website I developed.
<?php
$strFullname = $strEmail = $strMobile = $strPosition = "";
require 'assets/api/PHPMailer-master/PHPMailerAutoload.php';
//Create a new PHPMailer instance
$mail = new PHPMailer(true);
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
//$mail->SMTPDebug = 1;
//Ask for HTML-friendly debug output
//a$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = 'secure.emailsrvr.com';
// use
// $mail->Host = gethostbyname('smtp.gmail.com');
// if your network does not support SMsTP over IPv6
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "myemail#mailserver.com";
//Password to use for SMTP authentication
$mail->Password = "myaccountpassword";
//Set who the message is to be sent from, you can use your own mail here
$mail->setFrom('bpsourceph#gmail.com', '#noreply.bpsource.com');
//Set an alternative reply-to address
//$mail->addReplyTo('replyto#example.com', 'First Last');
//Set who the message is to be sent to
$mail->addAddress('testmail#mailserver.com', 'Firstname Lastname');
//Set the subject line
$mail->Subject = 'New application form sent from ***** Career page';
$mail->IsHTML(true);
//Attach an image file
//$mail->addAttachment('images/phpmailer_mini.png');
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$strFullname = $_POST['strFullname'];
$strEmail = $_POST['strEmail'];
$strMobile = $_POST['strMobile'];
$strPosition = $_POST['strPosition'];
//This part is where you will create your mail
$mail->msgHTML("Fullname: ".$strFullname."\nEmail: ".$strEmail."\nMobile Number: ".$strMobile."\nDesired Position: ".$strPosition);
//This part is for sending the mail
if (!$mail->send()) {
//If you want to check for errors. Uncomment the line below.
//echo "Mailer Error: " . $mail->ErrorInfo;
echo "<script>alert('Some error occured. Please try again later');</script>";
header("Refresh:2");
}
echo "<script>alert('Application form successfully sent!');</script>";
header("Refresh:2");
}
?>
Hope I am getting things clear for you. Regards! Goodluck!
Related
I have a simple contact form below---
<html>
<head>
<title>Sending HTML email using PHP</title>
</head>
<body>
<?php
$to = "contact#mydomain.com";
$subject = "This is subject";
$message = "<b>This is HTML message.</b>";
$message .= "<h1>This is headline.</h1>";
$header = "From:jayaryaa#gmail.com \r\n";
//$header .= "Cc:no-reply#skynetinfosolution.com \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$retval = mail ($to,$subject,$message,$header);
if( $retval == true ) {
echo "Message sent successfully...";
}else {
echo "Message could not be sent...";
}
?>
</body>
</html>
This script is working fine when I put my website email on place of $to , and when I enter my gmail id on place of FROM , my question is how can I send email to my gmail from my website email using mail function ? ,I have tried by putting my gmail id in place of $to and my website email in place of From but it's not working , My website is a shared linux hosting .
Take a look at the PHPMailer Github. When you use the PHP mail function, you are sending email directly from your web server.Sending mail via SMTP is recommended as email is sent from the mail server rather than local server. This script lets you send messages via your Google’s Gmail server. Example below
<?php
/**
* This example shows settings to use when sending via Google's Gmail servers.
* This uses traditional id & password authentication - look at the gmail_xoauth.phps
* example to see how to use XOAUTH2.
* The IMAP section shows how to save this message to the 'Sent Mail' folder using IMAP commands.
*/
//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
require '../vendor/autoload.php';
//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;
//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
// use
// $mail->Host = gethostbyname('smtp.gmail.com');
// if your network does not support SMTP over IPv6
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "username#gmail.com";
//Password to use for SMTP authentication
$mail->Password = "yourpassword";
//Set who the message is to be sent from
$mail->setFrom('from#example.com', 'First Last');
//Set an alternative reply-to address
$mail->addReplyTo('replyto#example.com', 'First Last');
//Set who the message is to be sent to
$mail->addAddress('whoto#example.com', 'John Doe');
//Set the subject line
$mail->Subject = 'PHPMailer GMail 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->msgHTML(file_get_contents('contents.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!";
//Section 2: IMAP
//Uncomment these to save your message in the 'Sent Mail' folder.
#if (save_mail($mail)) {
# echo "Message saved!";
#}
}
//Section 2: IMAP
//IMAP commands requires the PHP IMAP Extension, found at: https://php.net/manual/en/imap.setup.php
//Function to call which uses the PHP imap_*() functions to save messages: https://php.net/manual/en/book.imap.php
//You can use imap_getmailboxes($imapStream, '/imap/ssl') to get a list of available folders or labels, this can
//be useful if you are trying to get this working on a non-Gmail IMAP server.
function save_mail($mail)
{
//You can change 'Sent Mail' to any other folder or tag
$path = "{imap.gmail.com:993/imap/ssl}[Gmail]/Sent Mail";
//Tell your server to open an IMAP connection using the same username and password as you used for SMTP
$imapStream = imap_open($path, $mail->Username, $mail->Password);
$result = imap_append($imapStream, $path, $mail->getSentMIMEMessage());
imap_close($imapStream);
return $result;
}
Isn't because your host prevent emails sending from another domain for spam issues ?
Eventually you can add a transfert rule from your Skynet to Gmail adress.
I have this problem where when I receive an email sent from my localhost website, I get the wrong email address for the for the sender section ($mail->SetFrom($email, $name)). I get my own email address as the sender and not the one inputed in the text box on my website.
I've looked everywhere for some answers, sadly nothing worked. I've tried going on Chrome Account Settings and setting the less secure apps to ON. That didn't work.
I've tried multiple ways of setting the SetFrom email and name. NEED HELP!
<?php
$dir = __DIR__;
require_once("$dir/../PHPMailer-master/PHPMailerAutoload.php");
extract($_POST, EXTR_PREFIX_ALL, "P");
$name = $_POST['postName'];
$email = $_POST['postEmail'];
$subject = $_POST['postSubject'];
$message = $_POST['postMessage'];
$file = $_POST['postFile'];
echo "Name: ".$_POST['postName'];
echo "\n";
echo "Email: ".$_POST['postEmail'];
echo "\n";
echo "Subject: ".$_POST['postSubject'];
echo "\n";
echo "Message: ".$_POST['postMessage'];
echo "\n";
echo "File: ".$_POST['postFile'];
$mail = new PHPMailer;
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "mail.gmail.com"; // SMTP server
//$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "tls"; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 587; // set the SMTP port for the GMAIL server
$mail->Username = "xxxx#gmail.com"; // GMAIL username
$mail->Password = "xxxx"; // GMAIL password
$mail->SetFrom($email, $name);
$mail->AddReplyTo($email, $name);
$mail->addAddress("xxxx#gmail.com", "name");
$mail->AddAttachment("$file");
$mail->Subject = "$subject";
$mail->Body = "$message";
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
} ?>
This is an alert I set up showing all the POST parameters sent to the my PHP script. All the POST variables are there. The only problem is the SetFrom($email, $name)
Javascript Alert with POST Parameters
Gmail does not allow you to set arbitrary from addresses, though you can define preset aliases.
However, you shouldn't be trying to do this anyway. Putting user-provided value in the from address is a very bad idea as your messages will fail SPF checks because it's forgery. Put your own address in the from address (as well as the to address), and put the submitter's address in a reply-to header using the addReplyTo() method. You can see this working in the contact form example provided with PHPMailer:
//Use a fixed address in your own domain as the from address
//**DO NOT** use the submitter's address here as it will be forgery
//and will cause your messages to fail SPF checks
$mail->setFrom('from#example.com', 'First Last');
//Send the message to yourself, or whoever should receive contact for submissions
$mail->addAddress('whoto#example.com', 'John Doe');
//Put the submitter's address in a reply-to header
//This will fail if the address provided is invalid,
//in which case we should ignore the whole request
if ($mail->addReplyTo($_POST['email'], $_POST['name'])) {
...
I've been using PHPMailer for years and have been pretty happy with it, but now I'm trying to get a contact form working with an email address that is domain based but tied to Gmail via Google Apps. I.e. the MX record points to Google. I've added PHPMailer's Gmail example trying to get the setup to work, but at this point, I'm not connecting; I get this message:
SMTP ERROR: Failed to connect to server: Connection timed out (110)
SMTP connect() failed.
Mailer Error: SMTP connect() failed.
Here's my form processor code:
<?php
/**
* This example shows settings to use when sending via Google's Gmail servers.
*/
// CUSTOM: collect data from our web form
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$tel = $_REQUEST['tel'];
$subject = $_REQUEST['subject'];
$message = $_REQUEST['message'];
//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');
require 'mailer/PHPMailerAutoload.php';
//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 465;
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'ssl';
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "myemailaddress.com";
//Password to use for SMTP authentication
$mail->Password = "mypassword";
//Set who the message is to be sent from
//$mail->setFrom('from#example.com', 'First Last');
//Set an alternative reply-to address
//$mail->addReplyTo('replyto#example.com', 'First Last');
//Set who the message is to be sent to
$mail->addAddress('myemailaddress', 'my name');
//Set the subject line
$mail->subject = $subject;
$mail->Body = "Name : $name\n\n"
. "Email : $email\n"
. "Telephone : $tel\n"
. "Message :\n\n $message\n"
. "";
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
//$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__));
//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!";
}
To answer some questions in advance: yes, SSL rather than TLS is enabled in Gmail, and the MX record is changed at the host. I also did comment out some stuff, but as far as I can tell nothing that I need to get the form to actually send.
Beyond that, I don't even qualify as a hack with PHP; my primary skills are design, HTML and CSS, so I'm probably missing something obvious....
Thanks in advance.
i read a lot regarding this issue, and didn't really get clear answer
i simply have local server at home which has xampp and sendmail is working fine... i am using the sendmail folder that comes with xampp and all is fine
i have uncommented the sendmail path address... and put my localhost smtp information, user/pass all ok... works fine
there is another option to
force_sender=test#domain.com
when using this, it sends the email ok, i get in my normal email clinet an email from address: test#domain.com... that is fine
problem is i really want to define the sender name, like comes from MAIL SENDER
something like FROM: "John "
tried with quotes in the force_sender place, no change... i have this mailbox exisited in my xampp (hmail server) and i put the settings there to use FIRST NAME and LAST name like John Smith, but didn't work... all the time just coming like from address format: test#domain.com
this is also similar, but nobody really could help me to clear this doubt and get rest - yet
From address is not working for PHP mail headers
if you want to set sender name than you have to set into in headers. try this
$senderName="John";
$senderEmail= "test#domain.com";
$recipient = "recipient#domain.com";
$subject ="testmail";
$message="test message";
$headers = "From: " . $senderName . " <" . $senderEmail . ">";
$success = mail($recipient, $subject, $message, $headers );
A better approach in php is to use the library phpmailer.
Sending an e-mail would look like this and you can set any fields you want (off course you don't always need that many as in the example).
I guess $mail->FromName = "Your name"; is what you're looking for.
<?php
require '/whereeveritis/PHPMailerAutoload.php';
$mail = new PHPMailer;
//Enable SMTP debugging.
$mail->SMTPDebug = 3;
//Set PHPMailer to use SMTP.
$mail->isSMTP();
//Set SMTP host name
$mail->Host = "smtp.gmail.com";
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;
//Provide username and password
$mail->Username = "youraddress#gmail.com";
$mail->Password = "yourpasswordinplaintextyeah";
//If SMTP requires TLS encryption then set it
$mail->SMTPSecure = "tls";
//Set TCP port to connect to
$mail->Port = 587;
$mail->From = "name#gmail.com";
$mail->FromName = "Your name";
$mail->addAddress("name#example.com", "Recepient Name");
$mail->isHTML(true);
$mail->Subject = "Whatever good subject you like to use";
$mail->Body = "Mail body in HTML";
$mail->AltBody = "plain text version";
if(!$mail->send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent successfully";
}
I am facing an unexpected issue with a PHP mailfunction. The script sending email to all email address but not to my domain.
Suppose I send email to nitinsoni#gmail.com it was received but when I send email to nitin#mydomain.com it was not received.
I am using GoDaddy web hosting and PHP mail function. SMTP is also not working on GoDaddy server.
PHP code is as follows:
<?php
$to = 'nitin#mydomain.com';
//$to = 'nitinsonitest#gmail.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: nitinsonitest#gmail.com' . "\r\n" .
'Reply-To: nitinsonitest#gmail.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$r = mail($to, $subject, $message, $headers);
if($r) {
echo 'mail sent';
}else {
echo 'not sent';
}
die;
?>
And SMTP email via PHPMailer is not working as well:
<?php
echo "<pre>";
//die('ada');
require 'PHPMailerAutoload.php';
$mail = new PHPMailer();
$mail->Host = "relay-hosting.secureserver.net"; // your SMTP Server
$mail->IsSMTP();
$mail->PORT = 465;
$mail->SMTPDebug=true;
$mail->SMTPAuth = true; // Auth Type
$mail->SMTPSecure = "ssl";
$mail->Username = "user#gmail.com";
$mail->Password = "password";
$mail->Sender = "user#gmail.com";
$mail->From = "user#gmail.com";
$mail->AddReplyTo("user#gmail.com");
$mail->FromName = "user ";
$mail->AddAddress("recepient#gmail.com");
$mail->IsHTML(true);
$mail->Subject = "Test subject";
$mail->Body='Test Subject';
$mail->WordWrap = 50;
if($mail->Send())
{
echo"<script>alert('The Form has been posted ,Thank you');</script>";
}
else
{
echo 'mail error';
}
Suppose I send email to nitinsoni#gmail.com it was received but when
I send email to nitin#mydomain.com it was not received.
I am using GoDaddy web hosting and PHP mail function. SMTP is also
not working on GoDaddy server.
I doubt this has anything to do with the coding when using mail or PHPMailer. The thing is just because you send a mail, it doesn’t mean that the receiving end thinks the mail is valid. And chances are the receiving end—even if it is your domain—has decided a random e-mail sent off of a random server is simply SPAM.
I have posted a more detailed answer here, but when it comes to SPAM it basically boils down to this: Do you have an SPF (Sender Policy Framework) record setup for your domain? Do you also have a PTR (reverse DNS) record set for that domain?
If you do not have an SPF or PTR record, the chance of your message simply being flagged as SPAM is quite high.
If you are serious about sending mails off of your server, you need to at least get your SPF record & PTR record set.