How do I connect my PHP code to Heroku's addon 'SendGrid'? - php

I purchased a template that included a PHP contact form using AJAX I'm using Heroku to deploy my web application,(my portfolio), and SendGrid as my add-on in order to send API-driven emails from my portfolio. When I submit my form, I get a '500: Internal Server Error', so my question is, how to I integrate SendGrid into the PHP code I already have?
I'm unfamiliar with PHP and during research I did download composer and these files were automated:
- A vender folder
-composer.json file
-composer.lock file
Here is my Repo: https://github.com/Mendiolac/Portfolio
Here is my Portfolio link: https://cm-portfolio.herokuapp.com/
I tried the SMTP route where SendGrip gives you the steps to configure your application by connecting it their server and when I tested it was unsuccessful without an error message.
<?php
require '../vendor/autoload.php';
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
die('Sorry Request must be Ajax POST');
}
if(isset($_POST)) {
$name = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
$subject = filter_var($_POST["subject"], FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES);
$message = filter_var($_POST["message"], FILTER_SANITIZE_STRING);
if(!$contact_email_to || $contact_email_to == 'contact#example.com') {
die('The contact form receiving email address is not configured!');
}
if(strlen($name)<3){
die($contact_error_name);
}
if(!$email){
die($contact_error_email);
}
if(strlen($subject)<3){
die($contact_error_subject);
}
if(strlen($message)<3){
die($contact_error_message);
}
if(!isset($contact_email_from)) {
$contact_email_from = "contactform#" . #preg_replace('/^www\./','', $_SERVER['SERVER_NAME']);
}
$headers = 'From: ' . $name . ' <' . $contact_email_from . '>' . PHP_EOL;
$headers .= 'Reply-To: ' . $email . PHP_EOL;
$headers .= 'MIME-Version: 1.0' . PHP_EOL;
$headers .= 'Content-Type: text/html; charset=UTF-8' . PHP_EOL;
$headers .= 'X-Mailer: PHP/' . phpversion();
$message_content = '<strong>' . $name_title . '</strong> ' . $name . '<br>';
$message_content .= '<strong>' . $email_title . '</strong> ' . $email . '<br>';
$message_content .= '<strong>' . $message_title . '</strong> ' . nl2br($message);
$sendemail = mail($contact_email_to, $subject_title . ' ' . $subject, $message_content, $headers);
if( $sendemail ) {
echo 'OK';
} else {
echo 'Could not send mail! Please check your PHP mail configuration.';
}
}
?>

You are doing it correctly on https://github.com/Mendiolac/Portfolio/commit/0ad2fc815523a26f272f91bb192123c4caf41632 , just need to add keys to your .env file

Related

Mail Function is giving false return in PHP

I have tried sending email from a basic html form by php mail() function and It has given me false return
Code:
<?php
if(isset($_POST['submit'])){
$title = $_POST['title'];
$name = $_POST['first_name'];
$name1 = $_POST['last_name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$company=$_POST['lead_object'];
$skype= $_POST['skype_id'];
$to = 'himanshu#webkidukan.com';
$subject = 'Advertiser Form Details';
$from = 'ssing648#gmail.com';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Create email headers
$headers .= 'From: '.$from."\r\n".
'Reply-To: '.$from."\r\n" .
'X-Mailer: PHP/' . phpversion();
// Compose a simple HTML email message
$message = '<html><body>';
$message .= '<h1 style="color:#f40;">Hi Sir</h1>';
$message .= '<p style="color:#080;font-size:18px;">Details of Advertiser Form</p>';
$message .= '<p style="color:#080;font-size:18px;"><?php $title . " " . $name . " " . "?>wrote the following:"<?php . "\n\n" . $name . "\n\n" . $name1 . "\n\n" .$email . "\n\n" .$phone . "\n\n" .$company. "\n\n" .$skype. "\n\n"?> </p>';
$message .= '</body></html>';
$t = mail($to, $from, $message, $headers,$subject);
var_dump($t);exit;
if ($t) {
echo "Mail Sent. Thank you " . $name . " .We will contact you shortly.";
}else{
echo "Failed to send email. Please try again later";
}
echo "<script type='text/javascript'>alert('Thanks for filling out our form! We will look over your message and get back to you soon.')</script>";
echo "<script> window.location.href = 'advertiser.php';</script>";
}
?>
I have this issue in three forms together , hence posting one for the understanding the mistake, that I am doing. Can anyone of you help me with the same.Or should I go for the SMTP mail option.Also I am sending the form details in mail to the user.So also check that the way to send the flyer is right or not.
There are some unwanted PHP tags while appending message. try like this
$message = '<html><body>';
$message .= '<h1 style="color:#f40;">Hi Sir</h1>';
$message .= '<p style="color:#080;font-size:18px;">Details of Advertiser Form</p>';
$message .= '<p style="color:#080;font-size:18px;">'.$title." ".$name." wrote the following:"."\n\n".$name."\n\n".$name1."\n\n".$email."\n\n".$phone."\n\n".$company."\n\n".$skype."\n\n".'</p>';
$message .= '</body></html>';

PHP email form with attachments not working

I'm trying to use a PHP email form I found online that supports attachments, with a bit of extra code, but it's not working, I get a message saying "Sent", but no emails (I checked spam already).
Here is the php file:
function multi_attach_mail($to, $subject, $message, $senderMail, $senderName, $files){
$from = $senderName." <".$senderMail.">";
$headers = "From: $from";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
// preparing attachments
if(count($files) > 0){
for($i=0;$i<count($files);$i++){
if(is_file($files[$i])){
$message .= "--{$mime_boundary}\n";
$fp = #fopen($files[$i],"rb");
$data = #fread($fp,filesize($files[$i]));
#fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".basename($files[$i])."\"\n" .
"Content-Description: ".basename($files[$i])."\n" .
"Content-Disposition: attachment;\n" . " filename=\"".basename($files[$i])."\"; size=".filesize($files[$i]).";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
}
}
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $senderMail;
//send email
$mail = #mail($to, $subject, $message, $headers, $returnpath);
//function return true, if email sent, otherwise return fasle
if($mail){ return TRUE; } else { return FALSE; }
}
$message = "Customer Contact"
. "\n" . "Name: " . $_POST['fullName']
. "\n" . "Email: " . $_POST['email']
. "\n" . "Phone: " . $_POST['phone']
. "\n" . "Current Phone: " . $_POST['currentPhone']
. "\n" . "Address: " . $_POST['address']
. "\n" . "Retailer: " . $_POST['retailer']
. "\n" . "Product Type: " . $_POST['productType']
. "\n" . "Specific Item: " . $_POST['item']
. "\n" . "Purchase Date: " . $_POST['purchaseDate']
. "\n" . "Invoice Number: " . $_POST['invoiceNumber']
. "\n" . "Issue: " . $_POST['issue']
. "\n" . "How did the issue happen?: " . $_POST['how']
. "\n" . "When did the issue occur?: " . $_POST['when']
. "\n" . "Have you done anything to try correcting the issue?: " . $_POST['customerTry'];
$to = 'someEmail#gmail.com';
$from = $_POST['email'];
$from_name = $_POST['fullName'];
//attachment files path array
$files = $_FILES['files'];
$subject = 'Customer Contact From Service Form';
$html_content = $message;
//call multi_attach_mail() function and pass the required arguments
$send_email = multi_attach_mail($to,$subject,$html_content,$from,$from_name,$files);
//print message after email sent
echo $send_email?"<h1> Mail Sent</h1><br>".$message:"<h1> Mail not SEND</h1>";
My form looks like this:
<form NOVALIDATE action="processContact.php" enctype="multipart/form-data" id="claimsForm" method="post" name="claimsForm">
..lots of fields...
<div class="form-group">
<label class="control-label claimsForm-field-header" for="customerTry">Photos:</label>
<input type="file" id="files[]" name="files[]" multiple="multiple" />
</div>
<input class="green-btn" id="ss-submit" name="submit" type="submit" value="Submit">
</form>
The function came with the form I downloaded, so I don't think there is a problem with it. I've been playing around with the code and trying different things, but no luck (I'm not a PHP guy).
EDIT:
Based on the suggestion below, I tried using phpMailer, following the example they have, here is my php file now:
/**
* PHPMailer simple file upload and send example
*/
$msg = '';
$message = "Customer Contact"
. "\n" . "Name: " . $_POST['fullName']
. "\n" . "Email: " . $_POST['email']
. "\n" . "Phone: " . $_POST['phone']
. "\n" . "Current Phone: " . $_POST['currentPhone']
. "\n" . "Address: " . $_POST['address']
. "\n" . "Retailer: " . $_POST['retailer']
. "\n" . "Product Type: " . $_POST['productType']
. "\n" . "Specific Item: " . $_POST['item']
. "\n" . "Purchase Date: " . $_POST['purchaseDate']
. "\n" . "Invoice Number: " . $_POST['invoiceNumber']
. "\n" . "Issue: " . $_POST['issue']
. "\n" . "How did the issue happen?: " . $_POST['how']
. "\n" . "When did the issue occur?: " . $_POST['when']
. "\n" . "Have you done anything to try correcting the issue?: " . $_POST['customerTry'];
$to = 'murtorius#gmail.com';
$from = $_POST['email'];
$from_name = $_POST['fullName'];
//attachment files path array
$files = $_FILES['userfile'];
$subject = 'Customer Contact From Service Form';
if (array_key_exists('userfile', $_FILES)) {
// First handle the upload
// Don't trust provided filename - same goes for MIME types
// See http://php.net/manual/en/features.file-upload.php#114004 for more thorough upload validation
$uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['userfile']['name']));
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
// Upload handled successfully
// Now create a message
// This should be somewhere in your include_path
require 'php-mailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->setFrom($from, $from_name);
$mail->addAddress($to, 'TEST');
$mail->Subject = $subject;
$mail->msgHTML($message);
// Attach the uploaded file
$mail->addAttachment($uploadfile, 'Photos');
if (!$mail->send()) {
$msg .= "Mailer Error: " . $mail->ErrorInfo;
} else {
$msg .= "Message sent!";
}
} else {
$msg .= 'Failed to move file to ' . $uploadfile;
}
}
I changed the input file field name to 'userfile[]', but I get this:
Warning: sha1() expects parameter 1 to be string, array given in /home/zucora/service.zucora.com/processContact.php on line 35
Warning: move_uploaded_file() expects parameter 1 to be string, array given in /home/zucora/service.zucora.com/processContact.php on line 36
If I change the name to 'userfile' (without []) I get a blank screen and no email.

Customize a Php mail with html

I want to customize an php email with some html but I'm struggling with that...
After submit my form i receive the email but happen this
I was following this tutorial
I put the code i used.
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Alright, lets send the email already!
if ( empty( $errorString ) ) {
$mailbody .= '<html><body>';
$mailbody .= '<img src="//http://xxxx/xxxxx/wp-content/uploads/2015/06/email.jpg" alt="Website Change Request" />';
$mailbody .= '<table rules="all" style="border-color: #666;" cellpadding="10">';
$mailbody .= __('Nome:', 'ci_theme' ) . ' ' . $clientname . "\n";
$mailbody .= __('Email:', 'ci_theme' ) . ' ' . $email . "\n";
$mailbody .= __('Chegada:', 'ci_theme' ) . ' ' . $arrive . "\n";
$mailbody .= __('Saída:', 'ci_theme' ) . ' ' . $depart . "\n";
$mailbody .= __('Adultos:', 'ci_theme' ) . ' ' . $guests . "\n";
$mailbody .= __('Crianças:', 'ci_theme' ) . ' ' . $children . "\n";
$mailbody .= __('Quarto:', 'ci_theme' ) . ' ' . $room->post_title . "\n";
$mailbody .= __('Mensagem:', 'ci_theme' ) . ' ' . $message . "\n";
$mailbody .= __('Hora do Check-in (hh:mm):', 'ci_theme' ) . ' ' . $timeguest . "\n";
$mailbody .= __('Contacto:', 'ci_theme' ) . ' ' . $contactguest . "\n";
$mailbody .= __('Autorização:', 'ci_theme' ) . ' ' . $autorizo . "\n";
$mailbody .= __('Cama Extra:', 'ci_theme' ) . ' ' . $camaextra . "\n";
$mailbody .= "</table>";
$mailbody .= "</body></html>";
mail($to, $mailbody, $headers);
// If you want to receive the email using the address of the sender, comment the next $emailSent = ... line
// and uncomment the one after it.
// Keep in mind the following comment from the wp_mail() function source:
/* If we don't have an email from the input headers default to wordpress#$sitename
* Some hosts will block outgoing mail from this address if it doesn't exist but
* there's no easy alternative. Defaulting to admin_email might appear to be another
* option but some hosts may refuse to relay mail from an unknown domain. See
* http://trac.wordpress.org/ticket/5007.
*/
//$emailSent = wp_mail(ci_setting('booking_form_email'), get_option('blogname').' - '. __('Booking form', 'ci_theme'), $mailbody);
$emailSent = wp_mail(ci_setting('booking_form_email'), get_option('blogname').' - '. __('Formulário de Reserva','theme-text-domain', 'ci_theme'), $mailbody, 'From: "'.$clientname.'" <'.$email.'>');
$emailSent2 = wp_mail( $email, __('Booking Inquiry','theme-text-domain', 'ci_theme'), __('Thank you so much for your interest in Hotel Aveiro Center! We will get back to you within 24 hours to answer your request.','theme-text-domain','ci_theme'),'From: Hotel Aveiro Center <xxxx#xxxx>');
}
Here is a simple example I have done .
//build email to be sent
$to = $email;
$subject = $site_url;
$subject .= ": Activate Your Account";
$message = "
<html>
<head>
<title>Account Activation</title>
</head>
<body>
<h3>Account Activation</h3>
<p>Dear ".$user.", thank you for registering at ".$site_url.".</p>
<p>Please click on the link below to activate your account:</p>
<a href='".$site_url."/confirm_user_reg.php?activation_key=".$activation_key."'>http://www.".$site_url."</a>.
<p>If the above link does not work, copy and paste the below URL to your browser's address bar:</p>
<p><i>http://www.".$site_url."/confirm_user_reg.php?activation_key=".$activation_key."</i></p><br/>
<p>If you did not initiate this request, simply disregard this email, and we're sorry for bothering you.</p>
<br/><br/>
<p>Sincerely,</p>
<p>The ".$site_url." Team.</p>
</body>
</html>
";
// To send HTML mail, the Content-type header must be set
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";

sendmail.php does not work on mobile

Strange issue - my sendmail.php is working perfectly on desktop and on mobile devices only when requesting desktop websites (in Chrome app), but when using mobile site he does not work at all.
Can someone help me figure this out?
here is the code:
<?php
if(isset($_POST['email'])) {
if (!check_email($_POST['email']))
{
echo 'Please enter a valid email address<br />';
}
else send_email();
}
exit;
function check_email($emailAddress) {
if (filter_var($emailAddress, FILTER_VALIDATE_EMAIL)) {
return TRUE;
} else {
return FALSE;
}
}
function send_email() {
$message = "\nName: " . $_POST['name'] .
"\nEmail: " . $_POST['email'] ;
$message .= "\nMessage: " . $_POST['comment'] .
"\n\nBrowser Info: " . $_SERVER["HTTP_USER_AGENT"] .
"\nIP: " . $_SERVER["REMOTE_ADDR"] .
"\n\nDate: " . date("Y-m-d h:i:s");
$siteEmail = $_POST['receiver'];
$emailTitle = $_POST['subject'];
$thankYouMessage = "Thank you for contacting us, we'll get back to you shortly.";
if(!mail($siteEmail, $emailTitle, $message, 'From: ' . $_POST['name'] . ' <' . $_POST['email'] . '>'))
{
echo 'error';
}
else
{
echo 'success';
}
}
?>
You must make sure the mobile form has these two elements:
It is being submitted using method="POST".
Your email input has the attribute and value name="email".
I demonstrate where these things are set in the following code. This is incomplete, of course, it's just designed to show you where the two required parts must be.
<form ... method="POST">
...
<input type="text" name="email" ... >
...
</form>
I need to mention one more thing ...
That being said, what you're doing here is EXTREMELY INSECURE. You are allowing someone to set an email's from and two address on a web form. A (not so) clever hacker can easily write a script to turn your server into an open relay for spam or other evil activities. At minimum, you should remove $_POST['receiver'] and replace with with a hard-coded email address or at least not something that can be altered by an end-user when they POST to your form.
So I drilled down and found that the mobile form is directing submissions through this PHP file which was 404.
The issue now is, even when this file is avaiable, emails are not sent...
' . "\r\n"; $headers .=
'From: ' . "\r\n"; $headers = 'MIME-Version: 1.0' .
"\r\n"; $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$message .= "Name: " . $name . ""; $message .= "Subject: "
. $subject . ""; $message .= "Email: " . $email . ""; $message .= "Message: " . $message_text . "";
mail($to, $subject, $message, $headers, "-f noreplay#info.com");
echo 1; }
if(isset($_POST['sendmail']) && $_POST['sendmail'] == 1){
send_mail(); } ?>

getting warning Header may not contain more than a single header on wordpress

I'm learning WordPress and PHP and building a website at www.sunriselodging.com
When trying to enter data in a form, I get a PHP error warning saying 'header may not contain more than a single header' on line 6. I've tried solutions like checking the URL which are not related to PHP. I read a few solutions here that are PHP dependent and hence I cannot figure out what needs to be done here.
My code is below:
<?php
$reservation_message = $_POST['reservation_message'];
// Redirect back
Header('Location: '. $_POST['reservation-url'].'?message='.$reservation_message);
echo "<meta charset='utf-8'>";
// Loading variables from form
$blog_name = $_POST['blog_name'];
$blog_email = $_POST['blog_email'];
$reservation_email_subject = $_POST['reservation_email_subject'];
$reservation_email = $_POST['reservation_email'];
$reservation_email_switch = $_POST['reservation_email_switch'];
$room = $_POST['reservation-room'];
$checkin = $_POST['reservation-checkin'];
$checkout = $_POST['reservation-checkout'];
$people = $_POST['reservation-people'];
$name = $_POST['reservation-name'];
$email = $_POST['reservation-email'];
$phone = $_POST['reservation-phone'];
$message = $_POST['reservation-message'];
if($reservation_email_switch == 'on'){
// EMAIL TO CLIENT
// SET info to email
// From in format NAME <email>
$from = $blog_name.'<'.$blog_email.'>';
// Reply to in format NAME <email>
$reply = $blog_name.'<'.$blog_email.'>';
// Subject
$subject = $reservation_email_subject;
// Message
$message = $reservation_email;
//
$to = $email;
$headers = 'From: '. $from . "\r\n" .
'Reply-To: '. $reply . "\r\n" .
'X-Mailer: PHP/' . phpversion();
// Send mail
mail($to,$subject,$message,$headers);
// END OF EMAIL TO CLIENT
// ---------------------
}
// EMAIL TO RESERVATION CREW
$message = $_POST['reservation-message'];
$headers = 'From: '. $name . '<' . $email . '>' . "\r\n" .
'Reply-To: '. $name . '<' . $email . '>' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$subject = 'Reservation for room #' . $room;
$message = 'Name: ' . $name . '
Room: #' . $room . '
Check in: ' . $checkin . '
Check out: ' . $checkout . '
Number of people: ' . $people . '
Email: ' . $email . '
Phone: ' . $phone . '
' . $message;
$to = $blog_email;
// Send mail
mail($to,$subject,$message,$headers);
// END OF EMAIL TO RESERVATION CREW
// ---------------------
exit();
?>
The URL for the form is here - http://www.sunriselodging.com/reservation/. Apparently the form hasn't been sending emails either. Can someone please look at this and advise what's wrong with the code here?
I'll also appreciate if someone can direct me towards a good online PHP course for beginners (great if free).
Thank You,
Aadi
The whole problem with this here snippit is that you have 1) no conditions 2) no mail() function.
If you are going to use a header, you should probably have a condition. You should also probably have a condition to execute the emailer. Finally, you need to run this code before everything on the page (likely before the get_header() if on the page). Your workflow should go something similar to this:
<?php
// I assume you want the form to first process the email then forward
// so you need to check that the form was submitted
// Then check that the customer email is valid
if(isset($_POST['reservation-email']) && filter_var($_POST['reservation-email'], FILTER_VALIDATE_EMAIL)) {
// Loading variables from form
$blog_name = $_POST['blog_name'];
$blog_email = $_POST['blog_email'];
$reservation_email_subject = $_POST['reservation_email_subject'];
$reservation_email = $_POST['reservation_email'];
$reservation_email_switch = $_POST['reservation_email_switch'];
$room = $_POST['reservation-room'];
$checkin = $_POST['reservation-checkin'];
$checkout = $_POST['reservation-checkout'];
$people = $_POST['reservation-people'];
$name = $_POST['reservation-name'];
$email = $_POST['reservation-email'];
$phone = $_POST['reservation-phone'];
$message = $_POST['reservation-message'];
// Company email
$master = 'my#email.address';
// Use a from address
$header = "From: $email"."\r\n";
// Try mailing off the reservation to the hotel
if(mail($master,'Reservation Request',$message,$header)) {
// If success, send another email to the customer
$header = "From: no-reply#hotel.com"."\r\n";
mail($email,'Reservation Confirmation',$message,$header);
// What is the difference between this "reservation_message" and "reservation-message"??
$reservation_message = $_POST['reservation_message'];
// Redirect back
header('Location: '.$_POST['reservation-url'].'?message='.$reservation_message);
exit;
}
else {
echo 'Sorry, your reservation failed. Please contact customer service for reservations.';
exit;
}
}
?>
I was able to solve this after some research on Stack Overflow.
I added urlencode to the last string on the line containing header. I made:
Header('Location: '. $_POST['reservation-url'].'?message='.$reservation_message);
to look like this:
Header('Location: '. $_POST['reservation-url'].'?message='.urlencode($reservation_message));
To enable the mail function to send email I changed line 54 from
$headers = 'From: '. $name . '<' . $email . '>' . "\r\n" .
to this
$headers = 'From: Booking#hotel.com' . "\r\n" .
& line 70 from
$to = $blog_email;
to
$to = 'my#email.address';
Hope this will help anyone who's stuck in a situation similar to mine. A big THANK YOU to all the people who helped.

Categories