Need help sending email in PHP using Gmail SMTP - php

So I'm trying to follow the instructions here
http://www.9lessons.info/2011/07/send-mail-using-smtp-and-php.html
to use PHP to send out an email using my gmail account. But when I try to send a test email I get in the web browser this message: Error: could not connect to the host "smtp.gmail.com"
Here is are my two files (with my personal data edited)
Thanks for any help
<?php
print "1";
require("smtp.php");
require("sasl.php"); //SASL authentication
$from="support#yourwebsite.com";
$smtp=new smtp_class;
$smtp->host_name="smtp.gmail.com"; // Or IP address
$smtp->host_port=465;
$smtp->ssl=0;
$smtp->start_tls=1;
$smtp->localhost="localhost";
$smtp->direct_delivery=0;
$smtp->timeout=10;
$smtp->data_timeout=0;
$smtp->debug=1;
$smtp->html_debug=1;
$smtp->pop3_auth_host="";
$smtp->user="john#gmail.com"; // SMTP Username
$smtp->realm="";
$smtp->password="House22"; // SMTP Password
$smtp->workstation="";
$smtp->authentication_mechanism="";
print "3";
if($smtp->SendMessage(
$from,
array(
$to
),
array(
"From: $from",
"To: $to",
"Subject: $subject",
"Date: ".strftime("%a, %d %b %Y %H:%M:%S %Z")
),
"$message"))
{
print "Message sent to $to OK.";
}
else
print "Cound not seend the message to $to.\nError: ".$smtp->error;
print "4";
?>
==============================
<?php
$to="ralph#website.com";
$fn="First Name";
$ln="Last Name";
$name=$fn.' '.$ln;
$from="test#grove.net";
$subject = "Welcome to Website";
$message = "Dear $name,
Your Welcome Message.
Thanks
www.website.com
";
include('smtpwork.php');
?>

as per Gmail policy, You cannot use plain password (house22), you have to use encrypted password(Gh45515HGGujKkkHk5554), for that you need two way authentication should be enable on your gmail account. and after that, create Application Specific Password and then use that password for your SMTP, I hope that will work for you. here is the link1 Link2

Related

mail.php script not working for subscribe and contact page [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 5 years ago.
My web developer made this script to send notifications to people subscribing to my mailing list and the people who contact me, through the form on my website
The problem is, the recipients are not able to receive the emails, and I am not able to receive the notification on my mail id about a new subscriber or a contact
Sender id - notifications#llaveshagarwal.com
Moreover, the same script works on his server (which we used for testing) but doesn't work on my server
Is there a problem with my SMTP server settings ?
Also, I am using Google Apps for Gmail
Here is his script
What should I do ?
<?php
if($_POST['type'] == "subscribe") {
/*$to = "notifications#llaveshagarwal.com";
$subject = "New Email Subscriber";
$txt = "Name: ".$_POST['name']."\r\nFrom: ".$_POST['from'];
$headers = "From: ".$_POST['from'];
mail($to,$subject,$txt,$headers);
$to = $_POST['from'];
$subject = "Thank you for subscribing with us.";
$txt = "Hey ".$_POST['name']." ,\r\nGreetings from LLavesh Agarwal Textile Agency\r\nThank you for subscribing with us for Exclusive and Latest Catalogs and product launches.\r\nWe will update you soon.\r\n\r\nRegards,\r\nTeam LLavesh Agarwal\r\n\r\n*This is an automated Email. Please do not reply to this Email id. If you wish to talk to us, kindly Email us at hello#llaveshagarwal.com";
$headers = "From: notifications#llaveshagarwal.com";
mail($to,$subject,$txt,$headers);*/
$link = mysql_connect('localhost', 'llavesha_admin', 'Admin#1234');
$db= mysql_select_db('llavesha_contact_system', $link);
$insert='insert into subscribe (name,email) values ("'.$_POST["name"].'","'.$_POST["from"].'")';
if(mysql_query($insert)) {
echo "success";
} else {
echo "fail";
}
}
elseif($_POST['type'] == "contact") {
$to = "notifications#llaveshagarwal.com";
$subject = "New Contact";
$txt = "Name: ".$_POST['name']."\r\nContact: ".$_POST['mobile']."\r\nCategory: ".$_POST['bussiness_type']."\r\nDescription: ".$_POST['project_detail'];
$headers = "From: ".$_POST['from'];
mail($to,$subject,$txt,$headers);
$to = $_POST['from'];
$subject = "Thank you for contacting us.";
$txt = "Hey ".$_POST['name']." ,\r\nGreetings from LLavesh Agarwal Textile Agency\r\nThank you for contacting us.\r\nWe will update you soon !\r\n\r\nRegards,\r\nTeam LLavesh Agarwal\r\n\r\n*This is an automated Email. Please do not reply to this Email id. If you wish to talk to us, kindly Email us at hello#llaveshagarwal.com";
$headers = "From: notifications#llaveshagarwal.com";
mail($to,$subject,$txt,$headers);
echo "success";
}
?>
Are you working on windows (wamp)? Have you enabling php sendmail on php.ini? read: http://us3.php.net/manual/en/function.mail.php
or you can read: php mail() function on localhost
If you want to make it simpler, use phpmailer instead: https://github.com/PHPMailer/PHPMailer
How to use it by #pooria: How to configure PHP to send e-mail?
require('./PHPMailer/class.phpmailer.php');
$mail=new PHPMailer();
$mail->CharSet = 'UTF-8';
$body = 'This is the message';
$mail->IsSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->Username = 'me.sender#gmail.com';
$mail->Password = '123!##';
$mail->SetFrom('me.sender#gmail.com', $name);
$mail->AddReplyTo('no-reply#mycomp.com','no-reply');
$mail->Subject = 'subject';
$mail->MsgHTML($body);
$mail->AddAddress('abc1#gmail.com', 'title1');
$mail->AddAddress('abc2#gmail.com', 'title2'); /* ... */
$mail->AddAttachment($fileName);
$mail->send();

not able to send emails on gmail

I am able to send email to other emails are yahoo,hotmail,rediff but not able to send email on gmail.
Below is my code
<?php
// the message
$msg = "test text";
// send email
if(mail("myemail#gmail.com","My subject",$msg)){
echo "dsaf";
}
?>
How can I fix this issue.
Most mail services will filter out messages send by PHP mail(). Pear mail, on the other hand, allows for you to actually login to the gmail SMTP server when sending mail. This mail won't be filtered. Make sure when doing so that you alter your gmail settings to allow for less secure clients.
You have to enable SMTP relay service setting https://support.google.com/a/answer/2956491
Also check,
https://support.google.com/a/answer/176600?hl=en
Try this code.
$to = 'somemail#gmail.com';
$name = "John Doe";
$email = "john.doe#yahoo.com";
$message = "Test Message";
$subject = "Message from ".$name;
$message = $name . " ( ". $email . " ) wrote the following:" . "\n\n" . $message;
$headers = "From:" . $email;
mail($to,$subject,$message,$headers);

Issue with PHP mail form

Basically I have my PHP send an email to the person who signed up so then they their email will be verified. I did a test run and the link is generated with my database, its just the email that isn't making its way to the inbox. I'm not sure if its a delay or its an issue with the code, but any help would be much appreciated.
PHP For Email To Be Sent:
<?php
include('config.php');
// table name
$tbl_name=temp_members_db;
// Random confirmation code
$confirm_code=sha1(uniqid(rand()));
// values sent from form
$name=$_POST['name'];
$email=$_POST['email'];
// Insert data into database
$sql="INSERT INTO $tbl_name(confirm_code, name, email, password)VALUES('$confirm_code', '$name', '$email', '$password')";
$result=mysql_query($sql);
// if suceesfully inserted data into database, send confirmation link to email
if($result){
// ---------------- SEND MAIL FORM ----------------
// send e-mail to ...
$to=$email;
// Your subject
$subject="Your confirmation link here";
// From
$header="from: Colourity <your email>";
// Your message
$message="Your Comfirmation link \r\n";
$message.="Click on this link to activate your account \r\n";
$message.="http://www.colourity.com/confirmation.php?passkey=$confirm_code";
// send email
$sentmail = mail($to,$subject,$message,$header);
}
// if not found
else {
echo "Not found your email in our database";
}
// if your email succesfully sent
if($sentmail){
echo "Your Confirmation link Has Been Sent To Your Email Address.";
}
else {
echo "Cannot send Confirmation link to your e-mail address";
}
?>
You can use a PHP class like HTML Mime Mail (RMail) to act like a SMTP client to send your email. You will need a valid email account to use and your web server will still need to be able to send data out to whatever port you email account requires (usually port 25, 465, or 587).
I would recommend SwiftMailer. Instructions on using SMTP—to connect to another account to mail it—is located here.
require_once 'lib/swift_required.php';
// Create the Transport
$transport = Swift_SmtpTransport::newInstance('smtp.example.org', 25)
->setUsername('your username')
->setPassword('your password')
;
/*
You could alternatively use a different transport such as Sendmail or Mail:
// Sendmail
$transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs');
// Mail
$transport = Swift_MailTransport::newInstance();
*/
// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
// Create a message
$message = Swift_Message::newInstance('Wonderful Subject')
->setFrom(array('john#doe.com' => 'John Doe'))
->setTo(array('receiver#domain.org', 'other#domain.org' => 'A name'))
->setBody('Here is the message itself')
;
// Send the message
$result = $mailer->send($message);
But all that said, I would investigate if your host can handle localhost mailing since that is the easiest to use if you have that available.
I would recommend PHPmailer Library. Very easy to use for sure.
https://github.com/Synchro/PHPMailer

Sending an email verification after registering

I want, that users who register on my site, have to activate their account first, before using it. The problem is, that I don't get any email to my email test account.
Before I start posting a code, could the problem be, that I'm working currently on a local machine with xampp?
Otherwise, here is the code snippet
$random = substr(number_format(time() * rand(),0,'',''),0,10);
$insertMailVerify = $this->db->prepare("INSERT INTO mailverify (mailAddress, token, datetime) VALUES (:mailAddress, :token, :date)");
$insertMailVerify->execute(array(':mailAddress'=>$emailAddress,
':token'=>$random,
':date'=>$date));
$to = $emailAddress;
$subject = "Activating your Account";
$body = "Hi, in order to activate your account please visit http://localhost/FinalYear/activation.php?email=".$emailAddress." and fill in the verification code $random";
if(mail($to, $subject, $body))
{
echo ("<p>Message success</p>");
}
else {
echo ("<p>Message fail</p>");
}
Just in case you wonder where i take $emailAddress from: This is just a code snippet, i already let the software echo the email address, and it's correct. It even goes in the "Message success" if case, but I still can't get any email. What could be the problem?
After submit the form you can use a code or link and send it to the user email id
$message = "Your Activation Code is ".$code."";
$to=$email;
$subject="Activation Code For Talkerscode.com";
$from = 'your email';
$body='Your Activation Code is '.$code.' Please Click On This link Verify.php?id='.$db_id.'&code='.$code.'to activate your account.';
$headers = "From:".$from;
mail($to,$subject,$body,$headers);
echo "An Activation Code Is Sent To You Check You Emails";
Code from TalkersCode.com for complete tutorial visit http://talkerscode.com/webtricks/account-verification-system-through-email-using-php.php
in local host i think the best way is using phpmailer and gmail account
here the tutorial : http://www.web-development-blog.com/archives/send-e-mail-messages-via-smtp-with-phpmailer-and-gmail/
It seems your mail server SMTP is not configured correctly....
check the port and IP of SMTP server address.
Try to change you PHP.ini file like this and tell me if it works.
[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP = smtp.gmail.com
; http://php.net/smtp-port
smtp_port = 465 //if 465 is not working then try 25
If this is not working then there are a lot of tutorials of how to achieve what you are trying to do.
Here is one link: Send email from localhost
Had the same problem, but on linux.
1) Assuming your mail() function is working properly: the problem could be, that email is coming into spam-box (because these localhost mail systems are often marked as spambots, so email services are protecting emails from unverified host).
2) If mail() is not working, its not configured properly, if you follow some tutorial and configure it, which needs like 5 minutes, you will realise why not to use it:)
The best way for you is to use some free or paid smtp service. Very easy, quick and your emails wont be marked as spam. And install PEAR library to send email. Here is an example.
$from = 'from#domain.com';
$to = 'to#domain.com';
$subject = 'subject';
$body = 'Hello!';
$host = 'smtpserver.com';
$port = '25';
$username = 'yourlogin';
$password = 'yourpass';
$headers = array ('From' => $from, 'To' => $to, 'Subject' => $subject);
$smtp = Mail::factory('smtp', array ('host' => $host, 'port' => $port, 'auth' => true, 'username' => $username, 'password' => $password));
$mail = $smtp->send($to, $headers, $body);
if(PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
} else {
echo("<p>Message successfully sent!</p>");
}
To your verification code: instead of telling user to write down the verification code, better generate him the link, that he clicks his account gets activated. Something like
http://localhost/FinalYear/activation.php?email=some#email.com&token=79054025255fb1a26e4bc422aef54eb4
on registration page: generate the activation token like md5($email . '_sometext');
on activation page if(md5($_GET['email'] . '_sometext') == $_GET['token']) { activate.. }
please note, that it is just an example, there are 10 ways how it could be done :)

Using Gmail SMTP to send email with PHP

I have a problem I have been working on for about a week and can't find an answer. As a preface to this all, I have searched the internet for all sorts of things. There are a lot of answers for this problem, but none seem to be helping me.
I am somewhat new to PHP and a lot of the stuff I am asking for (been using it over the past few months). Let me get to the base of the problem:
I am on a school network with my own server set up in my dorm room. I am creating a website where I need to verify a user's email, but the basic PHP mail() function does not work. I have been told that I will need to use SMTP. So I decided the easiest and cheapest way was with Gmail SMTP. I created an account on Gmail called verify.impressions#gmail.com for this reason. Here is the code.
echo "starting mail sending";
require_once("pear/share/pear/Mail.php");
echo "1";
$from = "PersonA `<someone#gmail.com`>"; $to = "`<someoneElse#email.com`>"; $subject = "Activate your account"; $body = "Hey";
$host = "ssl://smtp.gmail.com"; $port = "465"; //also tried 587 $username = "someone#gmail.com"; $password = "password";
echo "2";
$headers = array ('From' => $from, 'To' => $to, 'Subject' => $subject);
echo "3";
$mailer_params['host'] = $host; $mailer_params['port'] = $port; $mailer_params['auth'] = true; $mailer_params['username'] = $username; $mailer_params['password'] = $password;
$smtp = Mail::factory('smtp', $mailer_params);
echo "4";
error_reporting(E_ALL);
echo "5";
if (PEAR::isError($smtp)) { die("Error : " . $smtp->getMessage()); }
echo "6";
$mail = $smtp->send($to, $headers, $body) or die("Something bad happened");
echo "7";
if (PEAR::isError($mail)) {echo($mail->getMessage();} else {echo(Message successfully sent!);}
echo "mail sent hopefully.";
So basically the code just stops at the line:
$mail = $smtp->send($to, %headers, $);
I have tried printing errors, but I just have no idea what to do now. Any tips and help is appreciated. Thanks!!
Use this class: http://www.phpclasses.org/package/14-PHP-Sends-e-mail-messages-via-SMTP-protocol.html
The sample code I use:
require("smtp/smtp.php");
require("sasl/sasl.php");
$from = 'youraddress#gmail.com';
$to = 'some#email.com';
$smtp=new smtp_class;
$smtp->host_name="smtp.gmail.com";
$smtp->host_port='465';
$smtp->user='youraddress#gmail.com';
$smtp->password='XXXXXXXXX';
$smtp->ssl=1;
$smtp->debug=1; //0 here in production
$smtp->html_debug=1; //same
$smtp->SendMessage($from,array($to),array(
"From: $from",
"To: $to",
"Subject: Testing Manuel Lemos' SMTP class",
"Date: ".strftime("%a, %d %b %Y %H:%M:%S %Z")
),
"Hello $to,\n\nIt is just to let you know that your SMTP class is working just fine.\n\nBye.\n"));
If you are you using Linux I recommend setting up postfix on your local machine and they asking that to relay the email forwards via an external SMTP service, in your case Gmail.
http://bookmarks.honewatson.com/2008/04/20/postfix-gmail-smtp-relay/
The reason is that your PHP script can timeout incase there's a delay contact Gmail. So you would use Postfix to queue the email on the local server, let the PHP script execution die and trust Postfix to send the email via Gmail.
If you are using Windows, I am sure you can find an equivalent SMTP relay application (should be built as a rough guess).
Many public networks block connections on the SMTP port to remote machines to stop spammers inside their network.
You have two choices:
Find a smtp server that uses a different port than 25
Use the official SMTP server of your school's network. There is always one since people need to send mails out.
I always use this to send mails using gmail as SMTP server.
Very Simple to configure

Categories