I am using smtp auth then also mail going into spam folder.
If the body of mail contains an external file (file_get_containts) then the mail is going in the Spam folder.
but, if the body of mail contains only string then the mail is going in the inbox folder.
Can someone please help me out with this?
here is my code:-
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
//Load Composer's autoloader
require 'vendor/autoload.php';
if( isset($_POST['name']) && isset($_POST['email']) && isset($_POST['phone']) && isset($_POST['message']) ){
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$m = nl2br($_POST['message']);
$mail = new PHPMailer();
$mail->isSMTP();
$mail->Host = 'mail.example.in';
$mail->SMTPAuth = true;
$mail->Username = 'info#example.in';
$mail->Password = 'nsdfdk^^dsfx7wffdsry8e^';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->From = 'info#example.in';
$mail->FromName = 'John Smith';
$mail->addCustomHeader('MIME-Version: 1.0');
$mail->addCustomHeader('Content-Type: text/html; charset=ISO-8859-1');
$mail->addAddress('example#gmail.com', 'Jay Senghani');
$mail->WordWrap = 50;
$mail->isHTML(true);
$mail->Subject = "New Enquiry from website";
$message = file_get_contents('emails/admin.html');
$patterns = array();
$patterns[0] = '/{name}/';
$patterns[1] = '/{email}/';
$patterns[2] = '/{number}/';
$patterns[3] = '/{message}/';
$replacements = array();
$replacements[0] = $name;
$replacements[1] = $email;
$replacements[2] = $phone;
$replacements[3] = $m;
$message = preg_replace($patterns, $replacements, $message);
$mail->Body = $message;
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent /n';
}
}
// For User Automated Email
if( isset($_POST['name']) && isset($_POST['email']) && isset($_POST['phone'])){
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$mail = new PHPMailer();
$mail->isSMTP();
$mail->Host = 'mail.example.in';
$mail->SMTPAuth = true;
$mail->Username = 'info#example.in';
$mail->Password = 'ndfgk^dfgg^gfdggfdgdfgdfx7wfy8e^';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
$mail->From = 'info#example.in';
$mail->FromName = 'John Smith';
$mail->addAddress($email, $name);
$mail->addCustomHeader('MIME-Version: 1.0');
$mail->addCustomHeader('Content-Type: text/html; charset=ISO-8859-1');
$mail->isHTML(true);
$mail->Subject = "Thank you for your interest Website ";
// $mail->addAttachment('Attachment Path', 'pdf');
$message = file_get_contents('emails/user.html');
$message = preg_replace('/{name}/', $name, $message);
$mail->Body = $message;
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent /n';
}
}
?>
Here is my admin template:-
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="emailWrapper">
<div id="emailHeader">
<div class="topBar"></div>
<a class="branding" href="http://example.com/" target="_blank" >
<img src="https://i.imgur.com/JME5efdRs.png">
</a>
</div>
<div id="emailContent">
<h2 class="greetings">
Dear Admin,
</h2>
<div class="content">
<p class="intro">
New enquiry from XYZ Website
</p>
<p>
<strong>Name :</strong> {name}
</p>
<p>
<strong>Number :</strong> {number}
</p>
<a class="email">
<strong>Email :</strong> {email}
</a>
<p>
<strong>Message :</strong> {message}
</p>
</div>
<div class="regards">
<h5><strong>Thanks & Regards,</strong></h5>
<h6>XyZ</h6>
</div>
</div> <!-- END #emailContent -->
<div id="emailFooter">
<div class="bottomBar">
<p>
© 2018 Xyz. All rights reserved
</p>
</div>
</div>
</div>
</body>
</html>
Troubleshooting email deliverability is tricky mostly due to the lack of details about the inner workings of anti-spam features at the main email service providers (Gmail, Msn, mail.com, Yahoo etc.). The main aspect of good email deliverability is usually your domain reputation. If you are just starting out with a new email domain most receiving services tend to be sceptic towards your first xx number of emails.
If your email contains invalid or poor html it will up the spam score. If you add attachments to it will certainly up the score.
I figure your emails without attachments are just below the threshold for ending up in the spam folder. When adding an attachment it gets just above the same threshold.
Most services also apply per-user rules, so the handling of your emails can be treated differently between receivers within the same service.
As a step in troubleshooting if PHPmailer is responsible for the poor delivery, I suggest setting up an email client like Mozilla Thunderbird and sending some emails from there.
That will help you figure out the source of the deliverability of your emails.
If you want to avoid thinking about deliverability you can spin up an account with SMTP services like Mailgun.
Related
I am trying to implement a form on my website - and make a PHPMailer send the content to my email address. I followed the directions from this website: https://www.codingsnow.com/2021/01/create-php-send-email-contact-form.html
But its not working. I tried different email addresses, I tried tls and other ports and many more - nothing. Its alway the same: When I click the submit button, nothing happens. There's neither a success nor a failed echo.
I could really need some help!
This is the form code:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<style type="text/css">
input, textarea {
margin-top: 10px;
}
</style>
</head>
<body>
<div class="container" style="margin-top:100px;">
<div class="row justify-content-center">
<div class="col-md-6 col-md-offset-3" align="center">
<input id="name" placeholder="Name" class="form-control">
<input id="email" placeholder="Email" class="form-control">
<input id="subject" placeholder="Subject" class="form-control">
<textarea class="form-control" id="body" placeholder="Email Body"></textarea>
<input type="button" onclick="sendEmail()" value="Send an Email" class="btn btn-primary"></type>
</div>
</div>
</div>
<script type="text/javascript">
function sendEmail() {
console.log('sending...');
var name = $("#name");
var email = $("#email");
var subject = $("#subject");
var body = $("#body");
if (isNotEmpty(name) && isNotEmpty(email) && isNotEmpty(subject) && isNotEmpty(body)) {
$.ajax({
url: 'sendEmail.php',
method: 'POST',
dataType: 'json',
data: {
name: name.val(),
email: email.val(),
body: body.val()
}, success: function (response) {
console.log(response)
}
});
}
}
function isNotEmpty(caller) {
if (caller.val() === "") {
caller.css('border', '1px solid red');
return false;
} else {
caller.css('border', '');
}
return true;
}
</script>
</body>
</html>
And this is the sendEmail.php:
<?php
use PHPMailer\PHPMailer\PHPMailer;
if(isset($_POST['name']) && isset($_POST['email'])){
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$body = $_POST['body'];
require_once "PHPMailer/PHPMailer.php";
require_once "PHPMailer/SMTP.php";
require_once "PHPMailer/Exception.php";
$mail = new PHPMailer();
//smtp settings
$mail->SMTPDebug = 2;
$mail->isSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->Username = "mymail#gmail.com";
$mail->Password = 'mypassword';
$mail->Port = 465;
$mail->SMTPSecure = "ssl";
//email settings
$mail->isHTML(true);
$mail->setFrom($email, $name);
$mail->addAddress("mymail#gmail.com");
$mail->Subject = ("$email ($subject)");
$mail->Body = $body;
if($mail->send()){
$status = "success";
$response = "Email is sent!";
}
else
{
$status = "failed";
$response = "Something is wrong: <br>" . $mail->ErrorInfo;
}
exit(json_encode(array("status" => $status, "response" => $response)));
}
if ($mail->send()) {
$status = "success";
echo "Email is sent!";
} else {
$status = "failed";
echo "Something is wrong: <br><br>" . $mail->ErrorInfo;
}
?>
Thank you for your time and knowledge!
Andre
P.S.: #Merchizm: Thanks, I have changed the code, now it looks like this:
<?php
require_once "PHPMailer/PHPMailer.php";
require_once "PHPMailer/SMTP.php";
require_once "PHPMailer/Exception.php";
use PHPMailer\PHPMailer\PHPMailer;
if(isset.... and so on
Is this, what you mean?
I also added the jQuery to the head of the html file like this:
<script src="jquery-3.3.1.min.js" type="text/javascript"></script>
<script type="text/javascript" src="jquery30102019.js"></script>
But nevertheless, it is not working. Still the same issue.
Do you have another idea?
Thanks Andre
The JQuery library is not included in the html file, the request may not be going because of this.
Require files before using class.
require_once __DIR__. "/PHPMailer/src/PHPMailer.php";
require_once __DIR__."/PHPMailer/src/SMTP.php";
require_once __DIR__."/PHPMailer/src/Exception.php";
use PHPMailer\PHPMailer\PHPMailer;
I think these will solve your problem.
I have spent a significant time looking for an answer, and tried every solution without success :/
Basically I want to use wamp server to create contact form that will be sent to my mail address.
I have wamp running but for the life of me I can't figure out why I wouldn't receive the mails, I either get the 404 page when submitting the form, or lately "Warning: mail(): SMTP server response: 553 sorry, that domain isn't in my list of allowed rcpthosts".
I am now looking for a solution that will at least send the form to my address, whether it's secured or not I just want to see an actual mail successfully sent.
Thanks !
edit: here is the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> Contact Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="page-wrap">
<div id="contact-area">
<form method="post" action="contactengine.php">
<label for="Name">Name:</label>
<input type="text" name="Name" id="Name" />
<label for="Email">Email:</label>
<input type="text" name="Email" id="Email" />
<label for="Message">Message:</label><br />
<textarea name="Message" rows="20" cols="20" id="Message"> </textarea>
<input type="submit" name="submit" value="Submit" class="submit-button" />
</form>
<div style="clear: both;"></div>
</div>
</div>
</body>
</html>
--then the contact engine--
<?php
$EmailFrom = "myadress#mail.com";
$EmailTo = "myadress#mail.com";
$Subject = "Nice & Simple Contact Form by CSS-Tricks";
$Name = Trim(stripslashes($_POST['Name']));
$Tel = Trim(stripslashes($_POST['Tel']));
$Email = Trim(stripslashes($_POST['Email']));
$Message = Trim(stripslashes($_POST['Message']));
// validation
$validationOK=true;
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
exit;
}
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $Name;
$Body .= "\n";
$Body .= "Tel: ";
$Body .= $Tel;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
// redirect to success page
if ($success){
print "<meta http-equiv=\"refresh\" content=\"0;URL=contactthanks.php\">";
}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}
?>
--then the thanks message--
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Strict//EN">
<head>
<title>A Nice & Simple Contact Form</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="page-wrap">
<img src="images/title.gif" alt="A Nice & Simple Contact Form" />
<p>By CSS-Tricks</p>
<br /><br />
<h1>Your message has been sent!</h1><br />
<p>Back to Contact Form</p>
</div>
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-68528-29";
urchinTracker();
</script>
</body>
</html>
Windows does not come with a Mail Server so just calling mail() will work as far as php is concerned but the mail goes nowhere.
You either need to install a mail server or use something like the PHPMailer library to allow you to send SMTP mails via something like Yahoo or Google.
I have a contact form script and when the user submits it, they get an email and I get one. But there's a problem with the "message" textarea in the HTML email. It puts it all in one line.
See how I type it out:
And then in the email sent to me (HTML) its all in one line:
As you can see it is all in one line. How can I get it to not be in this line?
This is my code:
<?php
// load the variables form address bar
$subject = $_POST["subject"];
$message = $_POST["message"];
$from = $_POST["from"];
$name = $_POST["name"];
$verif_box = $_POST["verif_box"];
// remove the backslashes that normally appear when entering " or '
$message = stripslashes($message);
$subject = stripslashes($subject);
$from = stripslashes($from);
$name = stripslashes($name);
$emailContent = "Hello Nathan,
".$name." is trying to contact WeeBuild Support. Here's what they submitted:
<br /><br />
<div style='background-color:#ccc;padding:10px;border:1px solid grey;'>
Name: <strong>".$name."</strong>
<br /><br />
Email: <strong>".$from."</strong>
<br /><br />
Subject: <strong>".$subject."</strong>
<br /><br />
Message:
<br /><br />
<strong>".$message."</strong>
<br /><br /><br />
Their IP Address: <strong>".$_SERVER['REMOTE_ADDR']."</strong>
</div>
<br /><br />
To email them back, simply reply to this message.";
$emailContents = "Hello ".$name.",
Thank you for contacting WeeBuild Support! This email is to let you know that we have received your support request and that we will reply soon.
For your record, here is what you submitted:
-----------------------------------------------------------------------------
Your Name: ".$name."
Your Email: ".$from."
Subject: ".$subject."
Message:
".$message."
-----------------------------------------------------------------------------
In the meanwhile, make sure to add support#weebuild.biz to your contact list/safe senders list so our emails don't end up in your junk folder.
We will be with you shortly!
Kind regards,
WeeBuild Support Team
www.WeeBuild.biz";
$emailContent = stripslashes($emailContent);
$emailContents = stripslashes($emailContents);
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". $from . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
// check to see if verificaton code was correct
if(md5($verif_box).'a4xn' == $_COOKIE['tntcon']){
// if verification code was correct send the message and show this page
mail("nathan#weebuild.biz", 'WeeBuild Contact Form: "'.$subject.'"', $emailContent, $headers);
mail($from, 'Thank you for contacting WeeBuild Support!', $emailContents, "From: support#weebuild.biz");
// delete the cookie so it cannot sent again by refreshing this page
setcookie('tntcon','');
} else if(isset($message) and $message!=""){
// if verification code was incorrect then return to contact page and show error
header("Location: index.php?name=$name&subject=$subject&from=$from&message=".urlencode($message)."&wrong_code=true");
exit;
} else {
echo "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">
<html><head>
<title>Access Denied</title>
<style type=\"text/css\">
body {
font-family: Arial, sans-serif;
}
</style>
</head><body>
<h1>Access Denied</h1>
<p>This page cannot be accessed directly. The needed variables to submit were not provided.</p>
</body></html>";
exit;
}
?>
Note: $emailContent is the email that goes to me and $emailContents is the email that goes to the user.
I tried using the str_replace() and that just caused parsing problems and I could not get that to work. I'm sure I wasn't using it right.
Can someone help me with this? Any help is highly appreciated.
use nl2br();
So edit this snippet
Message:
".$message."
to
Message:
".nl2br($message)."
You can use nl2br() function on $message to change newlines into <br /> tags.
I am using following code, copied from a website, for a contact page. But I am not getting any emails and the attached files don't find their way to my webserver folder /var/www/. Am I missing something here?
I am running this code on localhost.
email.php
ob_start();
$to = 'baltusaj#gmail.com';
/*$name = $_POST['name'];
$email = $_POST['email'];
$confirm_email = $_POST['confirm_email'];
$subject = $_POST['subject'];
$comments = $_POST['comments'];
$hidden = $_POST['hidden'];
$from = $email;
*/
$keys = array('name', 'email', 'confirm_email', 'subject', 'comments', 'hidden');
foreach($keys as $key)
{
$$key = isset($_POST[$key]) ? $_POST[$key] : null ;
}
print ('
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>Email</title>
<script type="text/javascript">
/*<![CDATA[*/
function progress(){
intWidth = parseInt(document.getElementById("container1").style.width) + 1;
if(intWidth <= 400){
document.getElementById("container1").style.width = intWidth+"px";
}else{
document.getElementById("container1").style.width = 0;
}
setTimeout("progress()",300);
}
/*]]>*/
</script>
</head>
<body>
');
//Make sure email and confirm email are the same
if (!empty ($hidden)) {
if ($email == $confirm_email) {
}else{
$email = '';
$confirm_email = '';
}
}
//Do a reg_ex check on the email
if (!empty ($hidden)) {
$regexp = "^([_a-z0-9-]+)(\.[_a-z0-9-]+)*#([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$";
if (eregi($regexp, $email))
{
}else{
$email = '';
$confirm_email = '';
}
}
// End of email checking
if (empty ($hidden)) {
print ('<div id="container2">
<h1 id="content_h1"><a name="text"> E-mail </a></h1> <p>Please use the following form to e-mail us:</p>
');
include ("form.php");
print ('</div>
<div id="container0" style="display: none;">
<p style="font-size: 15pt; font-family: sans-serif; color:#fd6700; background:#fff;">
Loading...
</p>
<div id="container1" style="width:0px; height:5px; background-color:#fd6700; margin-top:0px; text-align: left;"></div>
<p>Please be patient while your data is processed. This may take a few moments especially if you are uploading a file.</p>
</div>
');
}
if (!empty ($hidden)) {
if ($_FILES['fileatt']['error'] == 1){
print ('<h1 id="content_h1"><a name="text">There has been an error</a></h1>
<p>The maximum file size that can be uploaded using this form is 2 megabytes.
</p>');
}elseif ( (!empty ($name)) && (!empty ($email)) && (!empty ($comments))&& (!empty ($subject))) {
// Get html message content
$form_data = "<p>This email is from <span class=\"bold\">$name</span> \n\n ";
$form_data .= "<p>$comments</p>";
$message = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \n" .
" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"> \n" .
"<html xmlns=\"http://www.w3.org/1999/xhtml\"> \n" .
"<head> \n" .
" <meta http-equiv=\"content-type\" content= \n" .
" \"text/html; charset=iso-8859-1\" /> \n" .
"<style type=\"text/css\"> \n" .
"body { font-size: 9pt; font-family: verdana, sans-serif; color: #000; background:#fff; } \n" .
".bold { font-weight: bold; } \n" .
"</style> \n" .
"</head> \n" .
"<body>$form_data \n" .
"</body> \n" .
"</html> \n\n";
// Obtain file upload vars
$fileatt = $_FILES['fileatt']['tmp_name'];
$fileatt_type = $_FILES['fileatt']['type'];
$fileatt_name = $_FILES['fileatt']['name'];
$headers = "From: $from";
if (is_uploaded_file($fileatt)) {
// Read the file to be attached ('rb' = read binary)
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);
// Generate a boundary string
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// Add the headers for a file attachment
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
// Add a multipart boundary above the html message
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
// Base64 encode the file data
$data = chunk_split(base64_encode($data));
//We now have everything we need to write the portion of the message that contains the file attachment. Here's the code:
// Add file attachment to the message
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
}else{
// Generate a boundary string
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// Add the headers for a file attachment
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
// Add a multipart boundary above the html message
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
}
//That completes the modifications necessary to accommodate a file attachment. We can now send the message with a quick call to mail:
// Send the message
mail($to, $subject, $message, $headers);
$body = "Dear $name, \n\nThank you for your email. We will contact you as soon as possible regarding the matter. \n \n";
mail ($email, "Re: $subject", $body, 'From:you#your_email.com');
print ('<h1 id="content_h1"><a name="text"> Thank you </a></h1> <p>We will contact you as soon as possible. You will receive an automatic e-mail immediately confirming the reception of your email.</p>');
}else{
print ('<h1 id="content_h1"><a name="text">There has been an error</a></h1> <p>Please fill in all the compulsory fields correctly and then resubmit the form. Thank you.</p>');
include ("form.php");
}
}
// This is the end of the insert
print ('
</div>
</body>
</html>
');
ob_end_flush();
?>
form.php
<div id="form">
<form action="email.php" enctype="multipart/form-data" method="post" onsubmit="
document.getElementById('container0').style.display='';
document.getElementById('container2').style.display='none';
progress();
return true;">
<fieldset id="fieldset">
<label for="name">Contact name<span style="color: red;">*</span>:</label>
<input <?php if (!empty ($hidden)) { if (empty ($name)) { print 'style="background: pink;"'; } } ?> class="form_elements" id="name" type="text" name="name" value="<?php print "$name"; ?>" tabindex="1" />
<br />
<label for="email">E-mail address<span style="color: red;">*</span>:</label>
<input <?php if (!empty ($hidden)) { if (empty ($email)) { print 'style="background: pink;"'; } } ?> class="form_elements" id="email" type="text" name="email" value="<?php print "$email"; ?>" tabindex="1" />
<br />
<label for="confirm_email">Confirm e-mail<span style="color: red;">*</span>:</label>
<input <?php if (!empty ($hidden)) { if (empty ($confirm_email)) { print 'style="background: pink;"'; } } ?> class="form_elements" id="confirm_email" type="text" name="confirm_email" value="<?php print "$confirm_email"; ?>" tabindex="1" />
<br />
<label for="subject">Subject<span style="color: red;">*</span>:</label>
<input <?php if (!empty ($hidden)) { if (empty ($subject)) { print 'style="background: pink;"'; } } ?> class="form_elements" id="subject" type="text" name="subject" value="<?php print "$subject"; ?>" tabindex="1" />
<br />
<label for="comments">Comments<span style="color: red;">*</span>:</label>
<textarea <?php if (!empty ($hidden)) { if (empty ($comments)) { print 'style="background: pink;"'; } } ?>class="form_elements" id="comments" name="comments" cols="19" rows="5" tabindex="1"><?php print "$comments"; ?></textarea>
<br /><br />
<label for="fileatt">Attach document:</label>
<input id="fileatt" type="file" name="fileatt" tabindex="1" />
<br />
<input type="hidden" name="hidden" value="1" /><br />
<label for="submit"><span style="color: red;">*</span> Compulsory fields.</label>
<input id="submit" type="submit" value="Send" tabindex="1" />
</fieldset>
</form>
</div>
For the kajillionth time on this site: Don't build your own mime messages, it's unreliable and painful. Use Swiftmailer or PHPMailer instead. PHP's mail() function is highly unreliable and cannot produce ANY useful diagnostics as to why things are failing. Swift/PHPMailer will both tell you exactly why something blew up.
beyond that, nowhere do you seem to be doing a move_uploaded_file(), so your uploaded files will be auto-deleted by PHP when the script exits. You MUST deal with the files yourself, which means you have to write code to move the files to whatever place you want them stored in.
Are you running an SMTP server on your localhost?
I've tried several variations of ASP & PHP native & 3rd party mailer programs. I have hit a wall at almost every point between setting ini parameters from within the scripts to permission denied/transport fails.
I would be wasting time to show my examples for what I've tried so far. All my searches produce too many results with too many forums with too many 3rd party installations. I want to find the simplest way to set this up.
I don't care about fancy html formatting, attachments, colors, radio buttons, check boxes, etc... I would just love to find something with one text form field and a submit button that upon clicking it will send a simple email to me. I thought this would be a lot easier, but I never worked with IIS servers before.
A step by step approach or a link to a tested true resource would be greatly appreciated.
EDIT
The closest I got, with the least cryptic of error messages was with this asp code from tizag...
<%
'Sends an email
Dim mail
Set mail = Server.CreateObject("CDO.Message")
mail.To = Request.Form("To")
mail.From = Request.Form("From")
mail.Subject = Request.Form("Subject")
mail.TextBody = Request.Form("Body")
mail.Send()
Response.Write("Mail Sent!")
'Destroy the mail object!
Set mail = nothing
%>
The error I get back is:
CDO.Message.1 error '80040220'
The "SendUsing" configuration value is invalid.
For ASP.NET:
Install ASP.NET - I will assume that you have version 2, 3, or 3.5 of .NET installed.
In a command prompt:
cd \Windows\Microsoft.NET\Framework\v2.0.50727
aspnet_regiis.exe -i
Create a file in the appropriate virtual directory (maybe inetpub\wwwroot?) called email.aspx with the following text:
<%# Page language="c#" %>
<%# Import Namespace="System.Net.Mail" %>
<script runat="server">
protected void SendButton_Click(object sender, EventArgs e)
{
MailMessage message = new MailMessage(
"jane#contoso.com",
FromEmail.Text,
Subject.Text,
Message.Text);
SmtpClient client = new SmtpClient("127.0.0.1");
client.Send(message);
}
</script>
<html>
<body>
<form runat="server">
<table>
<tr>
<td>From Email:</td>
<td><asp:TextBox id="FromEmail" runat="server" /></td>
</tr>
<tr>
<td>Subject:</td>
<td><asp:TextBox id="Subject" runat="server" /></td>
</tr>
<tr>
<td>Message:</td>
<td><asp:TextBox id="Message" runat="server" TextMode="MultiLine" /></td>
</tr>
<tr>
<td></td>
<td><asp:Button id="SendButton" runat="Server" Text="Send" OnClick="SendButton_Click" /></td>
</tr>
</table>
</form>
</body>
</html>
You will need to change the string "127.0.0.1" to the IP address of your SMTP server and you will need to change the "jane#contoso.com" to the email address that you would like the mail sent to.
You could also require that the user enters an email address (and a valid one), a subject, and a message, by adding RequiredFieldValidator's and a RegularExpressionValidator.
Sending email in ASP using the CDO.Message object is really easy.
Here's a more complex sample with error handling and email address validation.
<%#LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<% Option Explicit %>
<%
Dim bPostback : bPostback = request.ServerVariables("REQUEST_METHOD") = "POST"
Dim sResult : sResult = ""
If bPostBack Then
Dim sSmtpServer : sSmtpServer = "your.smtp.server"
Dim sToEmail : sToEmail = "youremail#yourdomain.com"
Dim sFromEmail : sFromEmail = request.Form("email")
Dim sName : sName = request.Form("name")
Dim sSubject : sSubject = request.Form("subject")
Dim sBody : sBody = request.Form("body")
Dim oEmailer : Set oEmailer = New Emailer
oEmailer.SmtpServer = sSmtpServer
oEmailer.FromEmail = sFromEmail
oEmailer.ToEmail = sToEmail
oEmailer.Subject = sSubject
'oEmailer.HTMLBody = ""
oEmailer.TextBody = sBody
If oEmailer.sendEmail Then
sResult = "Email sent!"
Else
sResult = "Something went terribly wrong!(" + oEmailer.ErrMsg + ")"
End If
End If
'Simple Emailer
Class Emailer
Private oCDOM
Public FromEmail
Public ToEmail
Public Subject
Public HTMLBody
Public TextBody
Public SmtpServer
Public Port
Public ErrMsg
Private Sub Class_Initialize()
Set oCDOM = Server.CreateObject("CDO.Message")
TextBody = ""
'HTMLBody = ""
Port = 25
End Sub
'SQL IsNull equivalent
Private Function ifNull(vVar1, vVar2)
If Not IsNull(vVar1) Then
ifNull = vVar1
Else
ifNull = vVar2
End If
End Function
'Verifies that the Email address conforms to RFC standard.
Public Function isEmail(emailStr)
isEmail = False
If IsNull(emailStr) Then Exit Function
Dim emailPat : emailPat = "^([a-zA-Z0-9_\-])+(\.([a-zA-Z0-9_\-])+)*#((\[(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5])))\.(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5])))\.(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5])))\.(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5]))\]))|((([a-zA-Z0-9])+(([\-])+([a-zA-Z0-9])+)*\.)+([a-zA-Z])+(([\-])+([a-zA-Z0-9])+)*))$"
Dim loRE : Set loRE = New RegExp
loRE.IgnoreCase = True
loRE.Global = True
loRE.Pattern = emailPat
If loRE.Test(emailStr) Then isEmail = True
Set loRE = Nothing
End Function
Public Function sendEmail()
sendEmail = True
'On Error Resume Next
If IfNull(SmtpServer,"") = "" Then sendEmail = False
If Not isEmail(FromEmail) Then sendEmail = False
If Not isEmail(ToEmail) Then sendEmail = False
If IfNull(Trim(Subject),"") = "" Then sendEmail = False
If IfNull(Trim(HTMLBody),"") = "" And IfNull(Trim(TextBody),"") = "" Then sendEmail = False
If sendEmail = False Then Exit Function
oCDOM.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing")=2
oCDOM.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver")=SmtpServer
oCDOM.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=CINT(Port)
oCDOM.Configuration.Fields.Update
oCDOM.From = FromEmail
oCDOM.To = ToEmail
oCDOM.Subject = Subject
'oCDOM.HTMLBody = "<div>" & HTMLBody & "<div>"
oCDOM.TextBody = TextBody
oCDOM.Send
If Err.Number <> 0 Then
ErrMsg = Err.description
Err.Clear
sendEmail = False
Exit Function
Else
sendEmail = True
Exit Function
End If
End Function
Private Sub Class_Terminate()
Set oCDOM = Nothing
End Sub
End Class
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Emailer</title>
</head>
<body>
<p><strong><%=sResult%></strong></p>
<form action="" method="post" target="_self">
<label for="name">Name:</label><input id="name" name="name" type="text" size="50" maxlength="50" />
<br />
<label for="email">Email:</label><input id="email" name="email" type="text" size="50" maxlength="1024" />
<br />
<label for="subject">Subject:</label><input id="subject" name="subject" type="text" size="50" maxlength="1024" />
<br />
<label for="body">Body:</label>
<br />
<textarea id="body" name="body"></textarea>
<br />
<input name="Submit" value="Submit" type="submit" />
</form>
</body>
</html>
PHP:
use the builtin mail (...) method. If your not doing anything fancy you can use it directly.
Example:
form.php
<?php
if($_REQUEST['action']=='mail'){
$to="toaddress#gmail.com";
$from="fromaddress#gmail.com";
$subject="this is my subject";
$body=$_POST['body'];
$headers="From: $from\r\nTo: $to\r\nSubject: $subject\r\n";
if (stristr($to,"Content-Type")||stristr($subject,"Content-Type")||stristr($body,"Content-Type")||stristr($headers,"Content-Type")) {
header("HTTP/1.0 403 Forbidden");
echo "YOU HAVE BEEN BANNED FROM ACCESSING THIS SERVER FOR TRIGGERING OUR SPAMMER TRAP";
exit;
}
if(mail($to,$subject,$body,$headers)){
echo("Succesfully mailed to $to");
exit();
}else{
echo("Failed to send mail<br>");
}
}
?>
<form method=post>
<input type=hidden name=action value=mail>
<textarea name=body rows=4 cols=40><?php echo($_POST['body']); ?></textarea>
<input type=submit value=Send>
</form>
PS: The Content-Type check is to prevent someone from hijacking your email form.
PSS: This will use the mailserver as set in php.ini, that is the only setting that should matter.
For your ASP example, I think you are just missing the smtp server configuration:
<%
'Sends an email
Dim mail
Set mail = Server.CreateObject("CDO.Message")
mail.To = Request.Form("To")
mail.From = Request.Form("From")
mail.Subject = Request.Form("Subject")
mail.TextBody = Request.Form("Body")
mail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing")=2
'Name or IP of remote SMTP server
mail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.server.com"
'Server port
mail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25
mail.Configuration.Fields.Update
mail.Send()
Response.Write("Mail Sent!")
'Destroy the mail object!
Set mail = nothing
%>
As in the ASP.NET example, you would need to change "smtp.server.com" to your SMTP server's IP address.
This work for me using ASP Classic: http://www.powerasp.net/content/new/sending_email_cdosys.asp
Dim ObjSendMail
Set ObjSendMail = CreateObject("CDO.Message")
'This section provides the configuration information for the remote SMTP server.
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'Send the message using the network (SMTP over the network).
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") ="remoteserver"
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = False 'Use SSL for the connection (True or False)
ObjSendMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60
ObjSendMail.Configuration.Fields.Update
'End remote SMTP server configuration section==
ObjSendMail.To = "test#test.com"
ObjSendMail.Subject = "this is the subject"
ObjSendMail.From = "someone#someone.net"
' we are sending a text email.. simply switch the comments around to send an html email instead
'ObjSendMail.HTMLBody = "this is the body"
ObjSendMail.TextBody = "this is the body"
ObjSendMail.Send
Set ObjSendMail = Nothing