Sending email via PHP error - php

im a php beginner, and I am building a website, and website is supposed to let people send me email. the thing is i never knew anything about sending emails through php. I looked it up online and tried using the codes i found. The thing is my program says it sent the email but i never happen to get the email. I thought maybe it is because I am using apache server to test my php, and maybe it is gona work when I upload it to a real server??(yes this was a question)
Just in case, this is my code, and it is the all php code in my website, also form works fine, there is nothing wrong with it.
<?php
if (isset($_POST['name'])) {
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = "From: " . $_POST['name'] . ", " . $_POST['email'] . "\n Message: " . $_POST['message'];
try {
mail("serdarufuk95#gmail.com", $subject, $message, " ");
unset($_POST['name']);
header("Location: success.php");
}
catch (PDOException $e)
{
include 'index.html';
exit();
}
exit();
}
include 'contact2.php';
?>
is there a problem with the code? or do i have to call something from a library or anything or am i missing a code! HELP ME MAKE THIS WORK! when i execute it, it takes me to success.php, so i assumed nothing is wrong with my code, but you guys know better!

It might not work after uploading to a real server if the server's mail configuration has not been set yet. So I suggest you to use a better and simpler version in order to send mails through PHP: PHPMailer
require_once("class.phpmailer.php");
$mail = new PHPMailer();
$mail->AddAddress("mail#domain.com","Display name");
$mail->Subject= "Mail subject";
$mail->Body= "Mail content";
$mail->IsSMTP();
$mail->Host = "mail.domain.com";
$mail->SMTPAuth = true;
$mail->Username = "formmail#domain.com";
$mail->Password = "123456";
$mail->IsHTML(true); //true if you want to send html content. false for plain text message
$mail->From = $_POST['Email'];
$mail->FromName = $_POST['Name'];
$mail->Send();
You may download the class clicking here

Related

PHPMailer w/Gmail - Not Working

I have been recently learning PHP, and I need to be able to send emails using it.
I have found out that PHPMailer is a great way to send the mail, so I have tried it out. I have set up my code according to all of the examples that I can find, but I still am unable to get it to work.
Here is my PHP code:
<?php
error_reporting(E_ALL);
$fc = file_get_contents("http://redxtech.ca/fbm/");
echo $fc;
if (isset($_GET["name"]) && isset($_GET["email"]) && isset($_GET["m"])) {
$name = $_GET["name"];
$email = $_GET["email"];
$msg = $_GET["m"];
}
else {
$name = "Blank Name";
$email = "<email here>";
$msg = "Blank";
};
$e_msg = "FB:/nYou have recieved a new submission form from " . $name . " at <" . $email . ">./n/nIt says:/n/n" . $msg . "./n/nDo what you wish with this information./n~ Gabe";
require "PHPMailerAutoload.php";
$mail = new PHPMailer;
$mail->SMTPDebug = 1;
$mail->isSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->Username = "<my gmail>";
$mail->Password = "<my super secret password>";
$mail->SMTPSecure = "tls";
$mail->Port = 587;
$mail->setFrom("<my gmail>", "Red's Mailer");
$mail->addAddress("<my other email>", "Gabe");
$mail->addAddress("<another email>", "FB");
$mail->addReplyTo("<my other email>", "Gabe");
$mail->isHTML = true;
$mail->Subject = "New Submission";
$mail->Body = $e_msg;
$mail->AltBody = "This is an altbody.";
if(!$mail->send()) {
echo "<script>console.log('Mail was not sent')</script>";
$errInf = $mail->ErrorInfo;
echo "<script>console.log('Mailer Error: " . $errInf . "')</script>";
} else {
echo "<script>console.log('Mail was sent')</script>";
}
?>
When I click on the submit button to send the form on the previous page, it takes me to /mail.php?name=aName&email=anEmail&m=aMsg and echo's the page, but it isn't sending the email.
When I open up Chrome Dev Tools:
"The devicemotion event is deprecated on insecure origins, and support will be removed in the future. You should consider switching your application to a secure origin, such as HTTPS. See for more details."
However, I'm pretty sure that is caused by the embedded Vimeo players and not PHPMailer.
If anyone can give me a hand here that would be great :D
I fixed my own problem.
When I mentioned that I didn't think it was loading properly, that was half correct.
To fix it, I added the rest of the .php files into the same directory as the autoloader. I thought that the autoloader automatically included all of them.

PHP contact form, not receiving email [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 7 years ago.
So, here we go with silly question number too many to count!
I've made a very simple PHP contact form using tutorials from the internet (I still need to add security measures to it but I wanted to get it working first) When I click on the send button on my website I do get the message sent script however no email arrives in my in box.
Any ideas what I'm doing wrong? The website is currently hosted locally via XAMPP.
$name = $_POST['name'];
$company = $_POST['company'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$message = $_POST['message'];
$from = 'From: me#mywebsite.co.uk';
$to = 'me#mywebsite.co.uk';
$subject = 'Enquiry';
$body = "From: $name\n Company: $company\n Email: $email\n Telephone: $tel\n Message: $message\n";
if ($_POST['send']) {
if(mail($to, $subject, $body, $from)) {
echo '<p> Your message has been sent!</p>';
} else {
echo '<p>Message could not be sent.<br>Please check that you have completed the name, email and message fields and try again</p>';
}
}
Alright:
Step 1: check your error logs for any problems with the mail not being sent. Normally when installing an Apache inside windows the most people skip to set the from server and credentials.
I used WAMP alot and that one works normally only with an external account.
Step 2: If anything fails.
Download a mailer library and use Gmail to send the emails. Here is an tutorial on that : http://phpmailer.worxware.com/?pg=examplebgmail
Works great. Sure there is a lot of files in phpmailer but it works and easy to upgrade when new software versions are released.
As when I've previously set up contact forms I've been doing so using Code Igniter I didn't realise that I couldn't use mail() without installing a mail server.
Thanks to Parris Varney and RiggsFolly for pointing this out and thanks again to Riggs for letting me know that Code Igniter uses the PHPMailer library.
By using PHPmailer I was able to correct the code and get the form working perfectly in very short order.
For anyone interested the new code used with the latest version of PHPmailer is:
$name = $_REQUEST['name'];
$co = $_REQUEST['company'];
$email = $_REQUEST['email'];
$tel = $_REQUEST['tel'];
$message = $_REQUEST['message'];
require("PHPMailerAutoLoad.php");
$mail = new PHPMailer();
$mail->isSMTP();
$mail->Host = "mail.mydomain.co.uk";
$mail->SMTPAuth = true;
$mail->Username = "me#mydomain.co.uk";
$mail->Password = "password";
$mail->SMTPAutoTLS = false;
$mail->From = $email;
$mail->addAddress("me#mydomain.co.uk", "Me");
$mail->WordWrap = 50;
$mail->isHTML(true);
$mail->Subject = "Enquiry";
$mail->Body = "From: $name<br>Company: $co<br>Email: $email<br>Telephone: $tel<br>Message: $message";
$mail->AltBody = "From: $name Company: $co Email: $email Telephone: $tel Message: $message";
if(!$mail->Send())
{
echo "Message could not be sent";
}
echo "Message has been sent";
?>

PHP Mailer - Internal Server Error

I have been trying to make the contact form on my website to work and I've spent weeks trying to figure it out and I couldn't.
Here's the problem - I purchased a web template and it came with the PHPMailer. I'm now done plugging my content into the template, but the contact form has been a pain. I've followed the instructions the best I know on the PHP file, but it's giving me an "Internal Server Error" when I am testing the contact form.
Here's the code that came with my purchase:
$name = trim($_POST['name']);
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$site_owners_email = 'name#mydomain.com'; // Replace this with your own email address
$site_owners_name = 'My Name'; // Replace with your name
try {
require_once('/Beta-BRC/php/PHPMailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->From = $email;
$mail->FromName = $name;
$mail->Subject = "[WEB Form] ".$subject;
$mail->AddAddress($site_owners_email, $site_owners_name);
$mail->Body = $message;
$mail->Mailer = "smtp";
$mail->Host = "smtp.gmail.com"; // Replace with your SMTP server address
$mail->Port = 465;
$mail->SMTPSecure = "SSL";
$mail->SMTPAuth = true; // Turn on SMTP authentication
$mail->Username = "name#mydomain.com"; // SMTP username
$mail->Password = "mypassword"; // SMTP password
//echo "true";
if($mail->Send()) {
echo "true";
} else {
echo "Error sending: " . $mail->ErrorInfo;
}
} catch (Exception $e) {
echo $e;
}
Quick note - I've alrealy tried using a GMAIL account on this part but it still does not work.
$mail->Username = "name#mydomain.com"; // SMTP username
$mail->Password = "mypassword"; // SMTP password
There's no need to log into Gmail with phpmailer. Below is an example of my phpmailer function using the default settings.
public function sendEmail($toaddress,$toname,$subject,$message){
if($template = file_get_contents('/home/username/domains/mydomain.com/public_html/html/email-template.html')){
$template = str_replace("[SUBJECT]",$subject,$template);
$template = str_replace("[CONTENT]",nl2br($message),$template);
$mailer = new PHPMailer;
$mailer->XMailer = "Organization Name 4.0.0";
if($this->is_logged_in()){
$mailer->AddCustomHeader("X-Originating-User-ID",$this->acct['id']);
}
$mailer->AddCustomHeader("X-Originating-IP",$_SERVER['REMOTE_ADDR']);
$mailer->setFrom("outbound#mydomain.com","From Name");
$mailer->AddAddress($toaddress,$toname);
$mailer->Subject = $subject;
$mailer->MsgHTML($template);
$mailer->AltBody = $message;
return $mailer->Send();
}else{
return false;
}
}
The email address listed doesn't actually exist. The email is just being sent from my server and phpmailer just says it's from that email address.
Try modifying my function to suit your needs and let me know how that works.
Note: You'll need to make sure your mail server is turned on for this to work
Although you don't have to use my function at all. Try debugging your code by checking some error logs on your server. Typically in the apache error logs (if you're running apache, however). Checking error logs is a huge part of troubleshooting your code and often can help you become more proactive.
I hope this helps even the slightest!
The specific cause of the Internal Server Error is the incorrect path you've supplied to the require_once statement that loads the PHPMailer class.
The path you've supplied is /Beta-BRC/php/PHPMailer/class.phpmailer.php, where the correct statement should be
require_once('/home/trsta/public_html/Beta-BRC/php/PHPMailer/class.phpmailer.php');
or perhaps more generally:
require_once($_SERVER['DOCUMENT_ROOT'].'/home/trsta/public_html/Beta-BRC/php/PHPMailer/class.phpmailer.php');
You've provided effectively a URL, but PHP requires the path in the server file system, which is not the same.
That should get you past this error. It's possible that there are others.

Sending multiple emails with PHPmailer

Edit: I forgot I'd created the SendMail(); function myself, which is why the explanation doesn't mention at first what it does.
I'm having some trouble with PHPMailer (https://github.com/PHPMailer/PHPMailer) when attempting to send two emails, one directly after the other.
The script is almost completely 'out of the box', with only a few modifications such as a foreach loop to allow for multiple addresses, and everything still works perfectly.
However, if I attempt to call more than one instance of SendMail(); I get the error message:
Fatal error: Cannot override final method Exception::__clone() in .... online 0
Previously I was using the in-built mail(); function, which allowed me to use it as many times as I liked in quick succession , but it doesn't appear to be that simple with PHPmailer:
$to = me#me.com;
$to2 = me2#me2.com';
$headers = 'php headers etc';
$subject = 'generic subject';
$message = 'generic message';
mail($to, $subject, $message, $headers);
mail($to2, $subject, $message, $headers);
The above would result in two identical emails being sent to different people, however I can't easily replicate this functionality with PHPmailer.
Is there a way of stacking these requests so that I can send successive emails without it failing? Forcing the script to wait until the first email has been sent would also be acceptable, although not preferential.
As I mentioned I know it works when only one instance is called, but I don't seem to be able to re-use the function.
I haven't included the source code, although it is all available on the link provided above.
Thanks in advance
Edit as requested
// First Email
$to = array(
'test#test.com',
'test2#test.com',);
$subject = "Subject";
$message = $message_start.$message_ONE.$message_end;
sendMail();
// Second Email
$to = array(
'test#test.com',
'test2#test.com',);
$subject = "Subject";
$message = $message_start.$message_TWO.$message_end;
sendMail();
The above is how I want this to work, as it would work with mail();. The first email will work fine, the second will not.
SendMail() code
This is from the PHPmailer website, and is what is defined as SendMail();. The only difference from the example is the loop for AddAddress, and the inclusion of $to as a global variable.
$mail = new PHPMailer();
$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host = "smtp1.example.com;smtp2.example.com"; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "jswan"; // SMTP username
$mail->Password = "secret"; // SMTP password
$mail->From = "from#example.com";
$mail->FromName = "Mailer";
foreach($to as $to_add){
$mail->AddAddress($to_add); // name is optional
}
$mail->AddReplyTo("info#example.com", "Information");
$mail->WordWrap = 50; // set word wrap to 50 characters
$mail->AddAttachment("/var/tmp/file.tar.gz"); // add attachments
$mail->AddAttachment("/tmp/image.jpg", "new.jpg"); // optional name
$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";
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
You haven't posted this code that lets me make this a complete conclusion, but from the Exception and the way you've defined an overriding class inside a function, you probably have class.phpmailer.php loading every time like this:
require('class.phpmailer.php');
or
include('class.phpmailer.php');
You should change that line to
require_once('class.phpmailer.php');
The reason you need to change it to require_once is so that PHP will not load the class file the second time when you try to create the new/second PHPMailer class. Otherwise, the line class PHPMailer throws the __clone() exception.
Added an example below:
<?php
/**
* This example shows how to send a message to a whole list of recipients efficiently.
*/
//Import the PHPMailer class into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
error_reporting(E_STRICT | E_ALL);
date_default_timezone_set('Etc/UTC');
require '../vendor/autoload.php';
//Passing `true` enables PHPMailer exceptions
$mail = new PHPMailer(true);
$body = file_get_contents('contents.html');
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent, reduces SMTP overhead
$mail->Port = 25;
$mail->Username = 'yourname#example.com';
$mail->Password = 'yourpassword';
$mail->setFrom('list#example.com', 'List manager');
$mail->addReplyTo('list#example.com', 'List manager');
$mail->Subject = 'PHPMailer Simple database mailing list test';
//Same body for all messages, so set this before the sending loop
//If you generate a different body for each recipient (e.g. you're using a templating system),
//set it inside the loop
$mail->msgHTML($body);
//msgHTML also sets AltBody, but if you want a custom one, set it afterwards
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
//Connect to the database and select the recipients from your mailing list that have not yet been sent to
//You'll need to alter this to match your database
$mysql = mysqli_connect('localhost', 'username', 'password');
mysqli_select_db($mysql, 'mydb');
$result = mysqli_query($mysql, 'SELECT full_name, email, photo FROM mailinglist WHERE sent = FALSE');
foreach ($result as $row) {
try {
$mail->addAddress($row['email'], $row['full_name']);
} catch (Exception $e) {
echo 'Invalid address skipped: ' . htmlspecialchars($row['email']) . '<br>';
continue;
}
if (!empty($row['photo'])) {
//Assumes the image data is stored in the DB
$mail->addStringAttachment($row['photo'], 'YourPhoto.jpg');
}
try {
$mail->send();
echo 'Message sent to :' . htmlspecialchars($row['full_name']) . ' (' . htmlspecialchars($row['email']) . ')<br>';
//Mark it as sent in the DB
mysqli_query(
$mysql,
"UPDATE mailinglist SET sent = TRUE WHERE email = '" .
mysqli_real_escape_string($mysql, $row['email']) . "'"
);
} catch (Exception $e) {
echo 'Mailer Error (' . htmlspecialchars($row['email']) . ') ' . $mail->ErrorInfo . '<br>';
//Reset the connection to abort sending this message
//The loop will continue trying to send to the rest of the list
$mail->getSMTPInstance()->reset();
}
//Clear all addresses and attachments for the next iteration
$mail->clearAddresses();
$mail->clearAttachments();
}
In addition to #Amr most excellent code.
In order to use this in a cron fasion, two adds are useful.
$mail-> SMTPDebug = true;
$mail-> Debugoutput = function( $str, $level ) {_log($str);};
The function _log is up to you. Writing to a file, to a database or wherever. I personally have reduced this to
$mail-> Debugoutput = function( $str, $level ) {if( $level===3 ) {_log( $str ); } };
to only write the more juicier messages
the solution is to reset recipients data like this:
$Mailer->clearAddresses()
use your own variable as an instance of PHPMailer (instead of $Mailer)
$Mailer->clearAddresses()
This is the solution to avoid multiple msj to be send to the same recipient.

PHP Mailer Error: Mailer Error - must provide at least one recipient email address

I'm having and an issue with php mailer script. Using mamp the script works, but on the server I get an error (I've omitted sensitive info).
"Invalid address: [valid email] Mailer Error: You must
provide at least one recipient email address."
Heres my code:
require_once("includes/phpmailer/class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->Host = "smtp.emailsrvr.com";
$mail->SMTPDebug = 2;
$mail->Port = 25;
$mail->Username = "test#test.com";
$mail->Password = "test";
$mail->Subject = "Subject";
$mail->SetFrom($_POST['email'], $_POST['name']);
$mail->AddReplyTo($_POST['email'], $_POST['name']);
$address = "test#test.com";
$mail->AddAddress($address, "name");
$body = "<p>test</p>";
$mail->MsgHTML($body);
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
If it helps, I am using the rackspace email apps.
Im not very savy with php or server setups unfortunately so if anyone can help that would be great!
Just change this line:
$address = "[valid email]";
to something like:
$address = "test#test.te";
or to your own email, so you can test better, and it will work.
It's just stating that '[valid email]' is not actually a "valid email".
So i had no luck here, but I now know the issue stems from server mail settings rather then the script.
In the end I just went to using postmark.
I face this issue when my class name and my function name is same. Than i change the name of the function and it was resolved. Hope it will help anyone.

Categories