PHP Sendgrid - Sender name is not being sent in mail - php

I am working on PHP Sendgrid.. Everything is working fine.. but the problem is
I cannot add the Sender Name with from email somehow. I think it didn't captures the headers or what i have no idea.
P.S : I have executed this code on a separate server and it works. But when I try to send mail from the other server with same code it sends the email but doesn't set/show the Sender Name. Is it some server side issue I am using Laravel 4? please guide
$headers = "From: Coffe Email" . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
sendMail("myemail","mysubject","msg", $headers,$from="admin#email.com", "admin");
Function's Definition (sendMail) :
function sendMail($to, $subject, $message, $headers, $from = "", $from_name="", $to_name="")
{
require($_SERVER['DOCUMENT_ROOT']."/../sendgrid-php/sendgrid-php.php");
$email = new \SendGrid\Mail\Mail();
$email->setFrom($from, $from_name);
$email->setSubject($subject);
$email->addTo($to, $to_name);
$email->addContent("text/plain", strip_tags($message));
$email->addContent("text/html", $message);
$sendgrid = new \SendGrid($settings->send_grid_user);
try {
$response = $sendgrid->send($email);
print $response->statusCode() . "\n";
print_r($response->headers());
print $response->body() . "\n";
} catch (Exception $e) {
echo 'Caught exception: '. $e->getMessage() ."\n";
}
}

Related

How to retrieve the result of a php gmail api send mail and modify the label of the message

I'm sending small e-mail campaigns through my php site by using the gmail api.
I would like to know how to return of the the message was sent successfully or not and catch also the error in a variable. (for example if the email address format is not correct or a problem with gmail connection etc)
So I would like to get two variable:
$sent_success = 0 or 1 depending on the return.
$error_msg="the error message catched from gmail api"
On top of that after send the message I would like to apply a label to it so it's removed from the sent items in gmail.
Sending the message causes no problem.
Here's my code snippet:
$service = new Google_Service_Gmail($client);
$fromemail = "someemail#mail.com";
$strRawMessage = "From: fromname <$fromemail> \r\n";
$strRawMessage .= "To: ".$CONTACTS_FNAME." ".$CONTACTS_LNAME." <$RECIPIENT>\r\n";
$strRawMessage .= 'Subject: =?utf-8?B?' . base64_encode($EMAILSUBJECT) . "?=\r\n";
$strRawMessage .= "MIME-Version: 1.0\r\n";
$strRawMessage .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$strRawMessage .= 'Content-Transfer-Encoding: 8bit' . "\r\n\r\n";
$strRawMessage .= "$EMAILBODY\r\n";
$mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
$msg = new Google_Service_Gmail_Message();
$msg->setRaw($mime);
$service->users_messages->send("me", $msg);
Ok I solved it myself using try and catch method:
try {
SEND_MAIL($row['CONTACTS_EMAIL'],$EMAILSUBJECT,$EMAILBODY,$row['CONTACTS_FNAME'],$row['CONTACTS_LNAME']);
} catch (Exception $e) {
$err = $e->getMessage();
}

Php mail not working with more than one recipient

How come this piece of php code doesn't work with multiple recipient ?
It only works if $to has only one adress, like:
$to = 'aa#bb.com';
Edit
It works if email adresses are on the same domain.. For instance, if the website is www.example.com, emails such as xxx#example.com will work but yyy#other.com won't.
Solution
PHPMailer. It gives an easy way to configure SMTP.
Here is the initial code
<?php
//define the receiver of the email
$to = 'aa#bb.com, cc#dd.com, ee#ff.com';
// array with filenames to be sent as attachment
$files = array("a.zip","b.c","a.html");
// email fields: to, from, subject, and so on
$from = "mail#mail.com";
$subject ="My subject";
$message = "My message";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers = "From: $from";
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$mime_boundary}\n";
// preparing attachments
for($x=0;$x<count($files);$x++){
$file = fopen($files[$x],"rb");
$data = fread($file,filesize($files[$x]));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
// send
$ok = #mail($to, $subject, $message, $headers);
if ($ok) {
echo "<p>mail sent to $to!</p>";
} else {
echo "<p>mail could not be sent!</p>";
}
?>
Here is the final code
// PHPMailer
$mail = new PHPMailer;
// setting up PHPMailer
$mail->isSMTP();
$mail->Host = 'host.com';
$mail->SMTPAuth = false;
$mail->Port = xx;
$mail->setFrom($_POST['email'], $_POST['name']);
$mail->Subject = $_POST['subject'];
$mail->msgHTML($_POST['message']);
foreach($contacts as $contact)
$mail->addAddress($contact['email']);
// If the user has attached some files
foreach ($_FILES as $file)
$mail->addAttachment($file['tmp_name'], basename($file['name']));
$response = array("status" => $mail->send() ? "sent" : "error");
echo json_encode($response);
You need use proper RFC 2822 formating.
Don't use # because you don't know what is the error. If you format mails in format "user#example.com, anotheruser#example.com" it's correct and you need search problem elsewhere.
You can also see example #4 on http://php.net/manual/en/function.mail.php#example-3493 page.
although this is not a direct response to your issue, you could potentially save yourself trouble by using a pre-existing email sending library like either:
phpmailer
https://github.com/PHPMailer/PHPMailer
or simplesmtp
https://bitbucket.org/ghorwood/simplesmtp/

mPDF Auto Generated PDF Mailer sends blank Email

I am using mPDF class and am successfully able to generate an email with the following code. However, my email comes out blank. I am assuming but am not sure if this has something to do with my headers. It's hard for me to tell because I am getting my emails but am not able open the pdf it generates.
include("./mpdf.php");
$mpdf->debug = true;
$html2 = '
<div style="margin-left:3%;">Attach additional photos:
<input type="file" name="file" id="file" /></div><hr />';
echo $html2;
if ( isset( $_POST['submit'] ) ) {
$file_path = "webform.php";
$file_path_type = "application/pdf";
$mpdf=new mPDF('iso-8859-2');
$mpdf->WriteHTML($html);
$file_path_name = "eval.pdf";
$headers .= 'Content-type: text/html; charset=utf-8' . "\n";
$from = "info#myemail.com";
$to = $_POST['email'];
$ccto = $_POST['youremail'];
$subject = "New Form Submitted";
$message = "*** This is an automatically generated email,
please do not reply *** Someone in your association
has completed a survey.
$headers = "From: ".$from;
$headers.= "cc: " . $ccto . " <" . $ccto . ">" . "\n" ;
$file = fopen($file_path,'rb');
$data = fread($file,$file_path);
fclose($file);
$rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$rand}x";
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$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";
$data = chunk_split(base64_encode($data));
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$file_path_type};\n" .
" name=\"{$file_path_name}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$file_path_name}\"\n" .
"Content-Transfer-Encoding: base64\n" .
$data .= "\n\n" .
"--{$mime_boundary}--\n";
if(#mail($to, $subject, $message, $headers)) {
echo '<script language="javascript">';
echo 'alert("Document sent successfully!")';
echo '</script>';
echo "Sent!";
} else {
echo 'Failed';
}
}
exit;
PHP mail and mpdf users any help would be appreciated.
You're learning the hard way - Don't call mail() yourself because you will do it wrong; constructing and sending email messages is horribly complicated and full of pitfalls, as you're finding. Use a library, whether PHPMailer, SwiftMailer Zend_Mail etc, to do it and it will save you a great deal of hassle. You also need to check your two operations separately - first create a PDF, write it to a file and make sure it works correctly; Then write some code that sends a message and check that works; Then get it to send the PDF. Otherwise if you find it's not working, you won't be able to tell which part is broken.
Here is how I did it with MPDF and PHPMAILER.
I also have it so you can attach another file within my form that I made. Hope this helps you along the way.
include("mpdf/mpdf.php");
if ( isset( $_POST['submit'] ) ) {
$mpdf=new mPDF('c','Letter','','','10','10','10','10','','');
$mpdf->allow_charset_conversion=true;
$mpdf->charset_in='ISO-8859-2';
$mpdf->SetDisplayMode('fullpage');
$mpdf->WriteHTML(utf8_encode($html));
$emailAttachment = $mpdf->Output('serviceagreement.pdf', 'S');
//$emailAttachment = chunk_split(base64_encode($emailAttachment));
require("php_mailer/class.phpmailer.php");
$mail = new PHPMailer(true);
try {
$mail = new PHPMailer;
$mail->AddAddress('send email');
$mail->SetFrom('support#myorganization.com');
$mail->AddReplyTo($_POST['email1']);
$mail->Subject = 'Evaluation';
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
$mail->MsgHTML("*** Form attached! Please see the attached form (.pdf).");
$mail->AddStringAttachment($emailAttachment, $filename = 'serviceagreement.pdf',
$encoding = 'base64',
$type = 'application/pdf'); // attachment
if (isset($_FILES['attached']) &&
$_FILES['attached']['error'] == UPLOAD_ERR_OK) {
$mail->AddAttachment($_FILES['attached']['tmp_name'],
$_FILES['attached']['name']);
}
$mail->Send();
echo "<div style='margin-left:4%;'>Message Sent OK</div>\n";
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}}
?>'

php pear mail cant send the html formatted mail

Hi here my mail is working fine, but i dont know how to send a html formatted mail, because i am using pear mail!here i am using the code to send mail using php , first calling the mail.php and mime.php. $to mention which mail id you want to send a mail, to send a mail you need specify email id and password of email which is the sender mail.
<?php
if(isset($_POST['submit']))
{
require_once "Mail.php";//calling mail function
require_once 'Mail/mimePart.php';
$from = "you#localhost.com";
$to = "you#gmail.com";//your mail id
$CompanyName = $_POST['CompanyName'];
$mobile = $_POST['mobile'];
$email = $_POST['email'];
$paddress = $_POST['paddress'];
$subject = 'MOSONS Group';
$message = 'PersonName: ' .$CompanyName. "\n";
$message .= 'Mobile: ' .$mobile. "\n";
$message .= 'Email: ' .$email. "\n";
$message .= 'Message: ' .$paddress. "\n";
$host="ssl://smtp.gmail.com";
$port="465";
$username="you#gmail.com";// your email id
$password="yourpassword"; //password
$mime= "MIME-Version: 1.0\r\n";
$type= "Content-type: text/html\r\n";
$headers = array ('From' => $from,'To' => $to ,'Subject'=>
$subject,'Mime'=> $mime,'Contenttype'=> $type);
$smtp =# Mail::factory('smtp',array ('host'=>$host,'port'=>$port,'auth'=>true,'username'=>$username,'password'=>$password));
$mail = #$smtp-> send($to,$headers,$message);
if(#PEAR::isError($mail)){
echo ("<p>" .$mail->getmessage(). "</p>");
}
else
{
echo '<script type="text/javascript">alert("Thank You for Contacting us, our team will get in touch with you soon.!"); </script>';
}
}
?>
You are setting your headers incorrectly. e.g you're doing stuff like
'Contenttype'=> 'Content-type: text/html';
It should be just
'Content-Type' => 'text/html'
PEAR::Mail is a horribly crappy package. You should switch to something better, like PHPMailer or Swiftmailer.

Swift mailer connection refused with symfony1.2

Im having some problems sending mail. I have a ubuntu server running postfix as mailserver. The webapp is based on symfony 1.2 and has Swift 3 for mailing. Everyrhing is running on the same server. This is the code im trying to run:
public static function sendMailLocal($mailFrom, $mailto, $subject, $mailBody, $prevError)
{
$mailer = null;
try
{
$connection = new Swift_Connection_SMTP('localhost', '25');
$mailer = new Swift($connection);
// Create the mailer and message objects
$message = new Swift_Message($subject, $mailBody, 'text/html');
// Send
$mailer->send($message, $mailto, $mailFrom);
$mailer->disconnect();
}
catch (Exception $e)
{
if($mailer != null)
$mailer->disconnect();
throw new EmailTransferException ("There was an error while trying to send the email - locally:" . $e->getMessage() . " , first error:" . $prevError);
}
}
This is the error message im getting:
There was an error while trying to send the email - locally:The SMTP connection failed to start [localhost:25]: fsockopen returned Error Number 111 and Error String 'Connection refused' ,
It's kind of strange, because i did manage to send a mail without swift with this code:
//adresses are examples
$to = "john.doe#mail.com";
$sender_email = "someone#mail.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";
// Additional headers
$headers .= 'To: <'.$to.'>' . "\r\n";
$headers .= 'From: John Doe<'.$sender_email.'>' . "\r\n";
// Mail it
$success = mail($to, "test from server", "msg", $headers);
Anybody got any ideas about this??
thanks!
It's not a problem with Symfony or PHP - your local SMTP server is unreachable. You likely have a configuration problem with your mail server that is preventing the SMTP server being available on it's native port (25).

Categories