how to get e-mails on gmail account using PHPmailer - php

I'm really new to this field. I am working on my portfolio. I have made modal contact form (bootstrap) for "contact me". I'm not getting mails on my gmail account from php . I'm using PHP mailer and following is the code of my php with file name contact-form.php:
<?php
// check for form submission - if it doesn't exist then send back to contact form**
if (!isset($_POST['submit'])) {
$message=
'Name: '.$_POST['name'].'<br />
Email: '.$_POST['email'].'<br />
Message: '.$_POST['contact-message'];
require "phpmailer/class.phpmailer.php"; //include phpmailer class
// Instantiate Class
$mail = new PHPMailer();
// Set up SMTP
$mail->IsSMTP(); // Set up SMTP connection
$mail->SMTPAuth = true; // Connection with SMTP does require authorization
$mail->SMTPSecure = "ssl"; // Connect using a TLS connection
$mail->Host ="smtp.gmail.com"; //Gmail SMTP address
$mail->Port = 465; // Gmail SMTP port No idea what this is suppose to be
$mail->Encoding ='7bit';
$mail->Username = "mygmailid#gmail.com"; // Gmail address
$mail->Password ="Password"; // Gmail Password
// Compose
$mail->SetFrom($_POST['email'],$_POST['name']);
$mail->AddReplyTo($_POST['email'],$_POST['name']);
$mail->Subject = "Mail from Portfolio";
$mail->MsgHTML($message);
//Send To
$mail->AddAddress("recipientmail#gmail.com", "Recipient Name");
$result = $mail->Send();
$message = $result ? 'Successfully Sent!' : 'Sending Failed';
unset($mail);
}
I have linked all my html pages with contact-form.php as:
<form action="contactform.php" class="form-horizontal" method="post" enctype="text/plain">
When I clicked on the send message button it's directing me to the contact-form.php but nothing is happening.
Please Please help me out I have been stuck in this issue since last week.
Any suggestion or help will be highly appreciable.
Thank you in advance :)
Tayyaba.

i appreciate your code you have applied so far, as it is hard to debug your code, it would be better if you test your code with static info,
i have given a working example below:
$email = new PHPMailer();
$email->From = 'amrinder.salentro#gmail.com';
$email->FromName = 'Amrinder Singh';
$email->Subject = 'Hello';
$email->Body = "How are you karan";
$email->AddAddress( 'amrinder.salentro#gmail.com' );
$email->AddAttachment( 'PATH_OF_YOUR_FILE_HERE' , 'NameOfFile.pdf' ); //optional
return $email->Send();
i hope it would help you. please go with it...
thanks... :)

First of all, I suggest you start again using a known-good example for sending through gmail, and make sure you're using latest PHPMailer. As for your script, this line means that your mail handling code will only ever be run when the form is not submitted, and since this will result in sending errors, which you are not showing, you won't see anything happen!
if (!isset($_POST['submit'])) {
This should be:
if (isset($_POST['submit'])) {

Related

PHP to send email with buttons that prompts answer from recipient and send back value to actual database

I would like to ask, how can i make the email i sent out to consist of two buttons which is accept or reject that when the recipient click on reject/accept, the value actually sends back to the database.
Does anyone have idea on this method ?
PHP
$subject1="E-Calibration Registration Form Approval Notice for HOD";
$message1="Dear HOD, you currently have a pending E-Calibration Registration Form waiting for approval.";
$to1="67508#siswa.unimas.my";
//starting outlook
com_load_typelib("outlook.application");
if (!defined("olMailItem")) {define("olMailItem",0);}
$outlook_Obj1 = new COM("outlook.application") or die("Unable to start Outlook");
//just to check you are connected.
echo "<center>Loaded MS Outlook, version {$outlook_Obj1->Version}\n</center>";
$oMsg1 = $outlook_Obj1->CreateItem(olMailItem);
$oMsg1->Recipients->Add($to1);
$oMsg1->Subject=$subject1;
$oMsg1->Body=$message1;
$oMsg1->Save();
$oMsg1->Send();
echo "</br><center>Email has been sent succesfully</center>";
This is my php code for my email
The full solution consists of multiple parts:
Part 1: Send email script
I will use PHPMailer as an example. You should refer to the links for installation details.
<?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\SMTP;
use PHPMailer\PHPMailer\Exception;
//Load Composer's autoloader
require 'vendor/autoload.php';
//Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER; //Enable verbose debug output
$mail->isSMTP(); //Send using SMTP
$mail->Host = 'smtp.example.com'; //Set the SMTP server to send through
$mail->SMTPAuth = true; //Enable SMTP authentication
$mail->Username = 'user#example.com'; //SMTP username
$mail->Password = 'secret'; //SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; //Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Port = 587; //TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
//Recipients
$mail->setFrom('sender#example.com', 'Sender');
$mail->addAddress('67508#siswa.unimas.my');
//Content
$mail->isHTML(true); //Set email format to HTML
$mail->Subject = 'E-Calibration Registration Form Approval Notice for HOD';
$id = 12345;
$body = '<p>Dear HOD, you currently have a pending E-Calibration Registration Form waiting for approval.</p>';
$body.= '<p>Accept Reject</p>';
$mail->Body = $body;
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
Part 2: Response script
<?php
if(!isset($_GET['id'], $_GET['answer'])) {
die('missing parameters');
}
$id = (int)$_GET['id']; // assume ID is an integer
$answer = trim($_GET['answer']);
if(!in_array($answer, array('accept', 'reject'))) {
die('invalid answer');
}
// TODO: Save the info to MS Access DB
// read https://stackoverflow.com/questions/19807081/how-to-connect-php-with-microsoft-access-database for the codes
?>
So this functionality should start in the email you are sending. The email template or code should first of all be HTML to be able to accommodate the buttons. So the email mode should be HTML. These buttons can be linked to a form or direct links which denote Accept or Reject actions.
These can be the PHP file which then sends that information to the database.
<input type="submit" name="accept" value="Accept">
<input type="submit" name="accept" value="Reject">
Then in your PHP code, you can have your normal code to read these values and store them in the database.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$data = $_REQUEST['accept'];
// store in DB
}

Not getting emails from form with PHPmailer

I am trying to make a registration page with an email activation form using the php mailer library. After filling out the form and submitting the page I receive I don't receive any errors. I've checked my email multiple times and I don't seem to be receiving any emails. Since there are no errors, I'm not sure what else to look for. Has anyone ever had a similar problem before? Could it be an issue from gmail?
Heres my Send_mail.php
<?php
function Send_Mail($to,$subject,$body)
{
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$from = "batoosay#gmail.com";
$mail = new PHPMailer();
$mail->IsSMTP(true); // use SMTP
$mail->IsHTML(true);
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "tls://smtp.gmail.com"; // SMTP host
$mail->Port = 465; // set the SMTP port
$mail->Username = "batoosay#gmail.com"; // SMTP username
$mail->Password = "password"; // SMTP password
$mail->SetFrom($from, 'From Name');
$mail->AddReplyTo($from,'From Name');
$mail->Subject = $subject;
$mail->MsgHTML($body);
$address = $to;
$mail->AddAddress($address, $to);
$mail->Send();
}
?>
And here is my index.php
<?php
include 'db.php';
$msg='';
if(!empty($_POST['email']) && isset($_POST['email']) && !empty($_POST['password']) && isset($_POST['password']) )
{
// username and password sent from form
$email=mysqli_real_escape_string($connection,$_POST['email']);
$password=mysqli_real_escape_string($connection,$_POST['password']);
// regular expression for email check
$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/';
if(preg_match($regex, $email))
{
$password=md5($password); // encrypted password
$activation=md5($email.time()); // encrypted email+timestamp
$count=mysqli_query($connection,"SELECT uid FROM users WHERE email='$email'");
// email check
if(mysqli_num_rows($count) < 1)
{
mysqli_query($connection,"INSERT INTO users(email,password,activation) VALUES('$email','$password','$activation')");
// sending email
include 'Send_Mail.php';
$to=$email;
$subject="Email verification";
$body='Hi, <br/> <br/> We need to make sure you are human. Please verify your email and get started using your Website account. <br/> <br/> '.$base_url.'activation/'.$activation.'';
Send_Mail($to,$subject,$body);
$msg= "Registration successful, please activate email.";
}
else
{
$msg= 'The email is already taken, please try new.';
}
}
else
{
$msg = 'The email you have entered is invalid, please try again.';
}
}
// HTML Part
?>
BTW it loads for a very long time.
Please base your code on the gmail example provided with PHPMailer, as it is supplied with correct settings.
The syntax you've used in the Host property is fine (though not as common as setting SMTPSecure = 'tls'), but you're using the wrong port to use STARTTLS (which is what it uses when you specify tls) - you need to use Port = 587. This is probably what is causing your delay. If that doesn't work, read the troubleshooting guide.

PHP Mailer doesn't seem to work

I'm working on a registration page on a website where I need to implement a email verification.
I have installed PHPMailer-master on the server. The first part of the code is written directly in the registration php:
include('send_mail.php');
$to=$email;
$subject="Email verification";
$body='Hi, <br/> <br/> thank you for joining us! Please verify your email and get started using your account. <br/> <br/> '.$base_url.'activation/'.$activation.'';
Send_Mail($to,$subject,$body);
$msg= "Registration successful, a verification email has ben sent to you. Please activate this to get started.";
And the code in send_mail.php:
<?php
function Send_Mail($to,$subject,$body)
{
require 'PHPMailer-master/class.phpmailer.php';
require 'PHPMailer-master/PHPMailerAutoload.php';
$from = "*mywebsite*";
$mail = new PHPMailer();
$mail->IsSMTP(true); // use SMTP
$mail->IsHTML(true);
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "*my webhost's mailserver*"; // SMTP host
$mail->Port = 465; // set the SMTP port
$mail->Username = "*username*"; // SMTP username
$mail->Password = "*password*"; // SMTP password
$mail->SetFrom($from, '*mywebsite?*');
$mail->AddReplyTo($from,'*mywebsite?*');
$mail->Subject = $subject;
$mail->MsgHTML($body);
$address = $to;
$mail->AddAddress($address, $to);
$mail->Send();
}
?>
I'm fairly sure the information in send_mail.php is correct. I'm using the information I found on my configure mail client page on cPanel ("Secure SSL/TLS Settings").
When I try to register, the website goes white somehow. The account gets created on phpmyadmin. No error-log in public_html.
Any ideas?
UPDATE: Sorry for late response.
I've tried using the PHPMailer Test Page. When I try SMTP, the page just loads forever. When using Sendmail, I get the error "Could not execute: /usr/sbin/sendmail -t -i". When I use the QMAIL, it says the email was sent but I never recieve it.
BUT... when I use Mail, I recieve it successfully. Is "Mail" secure enough to use? What are the differences? And how should I implement it into the php code of the register page? I can't find any specific part in the PHPMailer Test Page code for the "mail" function.
Code looks like this now:
$email = $_POST['email'];
require 'PHPMailer-master/PHPMailerAutoload.php';
$mail = new PHPMailer(true);
try {
$mail->AddReplyTo('myemail');
$mail->AddAddress($email);
$mail->SetFrom('myemail');
$mail->AddReplyTo('myemail');
$mail->Subject = 'subject';
$mail->Message = 'message comes here';
$mail->Send();
echo "Message Sent OK<p></p>\n";
} catch (phpmailerException $e) {
echo $e->errorMessage();
} catch (Exception $e) {
echo $e->getMessage();
}
Error message: "Message body empty"

PHPmailer code works great to send to non-google apps email addresses but fails for google apps address

I am having a unique issue (I did a thorough search on SO before I attempted to ask this question.
When I use the PHPMailer to send to a gmail (or hotmail, etc) address, it works great. As soon as I change it to send to a Google Apps email address, I don't get any error message instead it tells me it was successfull but no emails come through.
Has anybody seen this issue before? Is my code missing something very particular that makes it a valid email to pass through Google Apps Servers (not sure if I am heading in the right direction here). Thank you!
Start of my Code:
<?php
require("/PHPMailer_5.2.0/class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Port = 465;
$mail->Host = 'smtp.gmail.com'; // "ssl://smtp.gmail.com" didn't worked
$mail->IsHTML(true); // if you are going to send HTML formatted emails
$mail->Mailer = 'mail';
$mail->SMTPSecure = 'ssl';
$mail->SMTPAuth = true;
$mail->Username = "******#dynamicsafetyfirst.com";
$mail->Password = "*******";
$mail->From = $_POST['email'];
$mail->AddAddress("someuser#gmail.com");
$mail->Subject = "First PHPMailer Message";
$mail->WordWrap = 50;
$mail->FromName = $_POST['name'];
$mail->Subject = $_POST['enquiry'];
$mail->Body = $_POST['comments']. "--By--".' name: '. $_POST['name']."--". 'email: ' .$_POST['email'];
if(!$mail->Send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent.';
}
?>
END OF CODE.
You're putting in quite a lot of effort to do things wrong. First up you're using a pretty old version of PHPMailer - go get the latest from github. Next, your code has many issues, so start again using the gmail example provided. Use tls on port 587. Do not set Mailer - you've already called isSMTP(), and overriding Mailer later is asking for trouble.
To see what is going on set $mail->SMTPDebug = 3;, and it will show you the whole SMTP conversation. At that point you may get some clue as to what is happening to your message.

how to send mail in php?

can anyone provide me the way of sending mail through php with attached object as well .plz i am new in this kindly help me in this. is there any server to be installed for this? the mail should this on any email account aswell plz help me in this.can any one provide me the link of tutorial i used the tutorial HERE it display me the error Fatal error: Call to undefined function IsSMTP() in C:\wamp\www\EMS3\mail.php on line 13 plz help me in this
There is an error in the example provided there. Use the following code.
require("phpmailer/class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP(); // send via SMTP
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "username#gmail.com"; // SMTP username
$mail->Password = "password"; // SMTP password
$webmaster_email = "username#doamin.com"; //Reply to this email ID
$email="username#domain.com"; // Recipients email ID
$name="name"; // Recipient's name
$mail->From = $webmaster_email;
$mail->FromName = "Webmaster";
$mail->AddAddress($email,$name);
$mail->AddReplyTo($webmaster_email,"Webmaster");
$mail->WordWrap = 50; // set word wrap
$mail->AddAttachment("/var/tmp/file.tar.gz"); // attachment
$mail->AddAttachment("/tmp/image.jpg", "new.jpg"); // attachment
$mail->IsHTML(true); // send as HTML
$mail->Subject = "This is the subject";
$mail->Body = "Hi,
This is the HTML BODY "; //HTML Body
$mail->AltBody = "This is the body when user views in plain text format"; //Text Body
if(!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent";
}
?>
update you also need to set the external SMTP server your using. if your using google. i believe its smtp.gmail.com
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->Secure = "ssl";
You can use an external PHP library for sending mail, which I have used internally on a localhost, but still configured the parameters to send to external sources. The package is Swift Mailer.
In localhost you can't send any mail. After hosting only this is possible.

Categories