Google Api Gmail - strange emails - php

I am using this function for send emails.
function sendMessage($to, $subject, $messageBody, $Cc)
{
$service = getGoogleGmailService();
$message = new \Google_Service_Gmail_Message();
$rawMessageString = "From: 'My name' <me>\r\n";
$rawMessageString .= "To: <" . $to . ">\r\n";
if (!empty($Cc)) {
$rawMessageString .= "Cc: <" . $Cc . ">\r\n";
}
$rawMessageString .= 'Subject: =?utf-8?B?' . base64_encode($subject) . "?=\r\n";
$rawMessageString .= "MIME-Version: 1.0\r\n";
$rawMessageString .= "Content-Type: text/html; charset=utf-8\r\n";
$rawMessageString .= 'Content-Transfer-Encoding: base64' . "\r\n\r\n";
$rawMessageString .= $messageBody . "\r\n";
$rawMessage = strtr(base64_encode($rawMessageString), array('+' => '-', '/' => '_'));
$message->setRaw($rawMessage);
try {
$message = $service->users_messages->send('me', $message);
return $message->getId();
} catch (Exception $e) {
return $e->getMessage();
}
}
In the first photo it is how the email should be structured, in fact everything arrives ok. Every so often, however, I receive a strange email, as in the second photo, as if it were still encoded or something else.
What could it be ?

Related

Send Email with attachment by using URL in Codeigniter

I would like to send an email with attachment.
I have no problem to send an email by using file path, but I prefer to set my attachment by using URL.
The email can sent successfully to my email without any attachment.
My PDF URL example: http://store/index.php/Store/GI/OrderID.pdf
Hope some can help me. Really Appreciate. Thank You.
Controller::
public function SendInvoice(){
$orderid = $this->uri->segment(3);
$result = $this->order->GetCustOrder($orderid);
unset($data);
$data = array(
$OrderID,
$result[0]->cust_id,
$result[0]->cust_name,
$result[0]->cust_email
);
$this->store_email->SendInvoiceToCust($data); //library
$this->session->set_flashdata('sent_email','Email has been sent to customer.');
redirect('Store/Index');
}
Library::
public function SendInvoiceToCust($data){
$message = "Dear Valued Customer, <br><br>Thank you for Purchased at Store. <br/><br/>Kindly refer the attachment to view your Invoice.";
//$attached_file = base_url(). 'index.php/Store/GI/' .$data[0]. '.pdf';
$form = base_url(). 'index.php/Store/GI/' .$data[0]. '.pdf';
$attachment = chunk_split(base64_encode($form));
$separator = md5(time());
$message .= "--" . $separator . PHP_EOL;
$message .= "Content-Type: application/octet-stream; name=\"\" . $data[0]. '.pdf'\"" . PHP_EOL;
$message .= "Content-Transfer-Encoding: base64" . PHP_EOL;
$message .= "Content-Disposition: attachment" . PHP_EOL . PHP_EOL;
$message .= $attachment . PHP_EOL . PHP_EOL;
$message .= "--" . $separator . "--";
$this->email->from('email#gmail.com', 'Store');
$this->email->to('email2#gmail.com');
$this->email->subject('Store INVOICE [Do not reply]');
$this->email->message($message);
$this->email->attach($attachment);
$this->email->send();
}
I cant comment yet but you should try setting content type and encoding the pdf.
The below is what I am currently using to send out an email with an attachement in codeigniter.
I have updated the response. This is currently how I am taking a pdf form and attaching it.
Its all done within the $message field with different content transfer and types being set.
$sender = "email#gmail.com";
$emails = "email2#gmail.com";
$subject = "Store INVOICE [Do not reply]";
$headers = "From: " . $sender . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$message = "";
$message = "--" . $separator . PHP_EOL;
$message .= "Content-Type: text/html; charset=\"iso-8859-1\"" . PHP_EOL;
$message .= "Content-Transfer-Encoding: 8bit" . PHP_EOL . PHP_EOL;
$message .= ($content = "Dear Valued Customer, <br><br>Thank you for Purchased at Store. <br/><br/>Kindly refer the attachment to view your Invoice.");
$message .= PHP_EOL . PHP_EOL;
$form = base_url(). 'index.php/Store/GI/' .$data[0]. '.pdf';
$attachment = chunk_split(base64_encode($form));
$separator = md5(time());
$headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: 7bit";
$message .= "--" . $separator . PHP_EOL;
$message .= "Content-Type: application/octet-stream; name=\"" . $data[0]. '.pdf'\"" . PHP_EOL;
$message .= "Content-Transfer-Encoding: base64" . PHP_EOL;
$message .= "Content-Disposition: attachment" . PHP_EOL . PHP_EOL;
$message .= $attachment . PHP_EOL . PHP_EOL;
$message .= "--" . $separator . "--";
$result = mail($emails, $subject, $message, $headers);

Sending E-Mail in PHP

I tried almost everything. I just want to send e-mail.
My First Code:
<?php
$to = "yourgmail#gmail.com";
$subject = "HELLO";
$body = "HI!";
try {
mail($to, $subject, $body);
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
It isn't working. No error message, not working.
My Second Code:
function send_mail('mygmail#gmail.com','yourgmail#gmail.com','HELLO','HI!')
{
$headers = '';
$headers .= "From: $from\n";
$headers .= "Reply-to: $from\n";
$headers .= "Return-Path: $from\n";
$headers .= "Message-ID: <" . md5(uniqid(time())) . "#" . $_SERVER['SERVER_NAME'] . ">\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Date: " . date('r', time()) . "\n";
mail($to,$subject,$body,$headers);
}
It isn't working too.
Please help me :)
Does this work?
First part:
<?php
$to = "yourgmail#gmail.com";
$subject = "HELLO";
$body = "HI!";
$from = "mygmail#gmail.com";
send_mail($to,$from,$subject,$body);
?>
Second part:
<?php
function send_mail($to,$from,$subject,$body) {
$headers = '';
$headers .= "From: $from\n";
$headers .= "Reply-to: $from\n";
$headers .= "Return-Path: $from\n";
$headers .= "Message-ID: <" . md5(uniqid(time())) . "#" . $_SERVER['SERVER_NAME'] . ">\n";
$headers .= "MIME-Version: 1.0\n"; $headers .= "Date: " . date('r', time()) . "\n";
mail($to,$subject,$body,$headers);
}
?>
I'm not sure if you can send mail via your gmail using php mail function, never looked into it, this should work for name#yourdomain.com

Unable to send email with PHP

Ok, I'm seriously stuck on this despite having previously asked a related question and having worked on this all morning.
The problem is basic - I cannot send email using PHP from a new app I'm starting. The mailhost is localhost and it does not require authentication. I can checkout a previous app I wrote that also uses the PHP mail function and it works. The php.ini file is the same in both cases, and both cases therefore use localhost.
Both the working app and the new app both have swiftmailer installed using composer, but in both the working example and in this example swiftmailer is not used.
Here is the actual code I want to work:
// Determine headers
$uid = md5(uniqid(time()));
$headers = "From: " . $this->fromAddress . " <" . $this->fromName . ">\r\n";
$headers.= "Reply-To: " . $this->fromAddress . " <" . $this->fromName . ">\r\n";
if ($this->cc != "") { $headers .= "CC: ".$this->cc."\r\n"; }
if ($this->bcc != "") { $headers .= "BCC: ".$this->bcc."\r\n"; }
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"" . $uid . "\"\r\n\r\n";
$headers .= "This is a multi-part message in MIME format.\r\n";
$headers .= "--" . $uid . "\r\n";
$headers .= "Content-type:text/html; charset=iso-8859-1\r\n";
$headers .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$headers .= $this->body . "\r\n\r\n";
// Optionally attach a file
foreach ($this->attachments as $attachment) {
$fileName = basename($attachment);
$fileSize = filesize($attachment);
$handle = fopen($attachment, "r");
$content = fread($handle, $fileSize);
fclose($handle);
$content = chunk_split(base64_encode($content));
$headers .= "--" . $uid . "\r\n";
$headers .= "Content-Type: application/octet-stream; name=\"" . $fileName . "\"\r\n";
$headers .= "Content-Transfer-Encoding: base64\r\n";
$headers .= "Content-Disposition: attachment; filename=\"" . $fileName . "\"\r\n\r\n";
$headers .= $content."\r\n\r\n";
unlink($attachment);
}
// Conclude headers
$headers .= "--".$uid."--";
// Send the email
$mail_sent = mail($this->toAddress,$this->subject,'',$headers);
if (!$mail_sent) {
throw new Exception('Email failed to send');
}
This code throws the exception, "Email failed to send". I can confirm that $this->toAddress is a valid email address and that $this->subject is a valid subject, and that $this->fromAddress is a valid email address, and that $this->body is a valid body, only a few characters long.
In attempting to boil this down to the simplest example, I tried the following code:
<?php
// The message
$message = "Line 1\r\nLine 2\r\nLine 3";
// In case any of our lines are larger than 70 characters, we should use wordwrap()
$message = wordwrap($message, 70, "\r\n");
// Send
$result = mail('lowens#mycompany.com', 'My Subject', $message);
if (!$result) {
error_log("fail");
}
?>
That logs "fail".
Just to confirm that localhost works, I re-checked out code that works. Here's the code that works:
// Determine headers
$uid = md5(uniqid(time()));
$headers= "From: " . $login->getUser() . " <" . $login->getUserEmail() . ">\r\n";
$headers.= "Reply-To: " . $login->getUser() . " <" . $login->getUserEmail() . ">\r\n";
if ($bcc != "") { $headers .= "BCC: ".$bcc."\r\n"; }
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$headers .= "This is a multi-part message in MIME format.\r\n";
$headers .= "--".$uid."\r\n";
$headers .= "Content-type:text/html; charset=iso-8859-1\r\n";
$headers .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$headers .= $message."\r\n\r\n";
// Optionally attach a file
foreach ($attachedFilePaths as $attachedFilePath) {
$fileName = basename($attachedFilePath);
$fileSize = filesize($attachedFilePath);
$handle = fopen($attachedFilePath, "r");
$content = fread($handle, $fileSize);
fclose($handle);
$content = chunk_split(base64_encode($content));
$headers .= "--".$uid."\r\n";
$headers .= "Content-Type: application/octet-stream; name=\"".$fileName."\"\r\n"; // use different content types here
$headers .= "Content-Transfer-Encoding: base64\r\n";
$headers .= "Content-Disposition: attachment; filename=\"".$fileName."\"\r\n\r\n";
$headers .= $content."\r\n\r\n";
unlink($attachedFilePath);
}
$headers .= "--".$uid."--";
// Send the email
$mail_sent = #mail($toAddr,$subject,'',$headers);
// Save this email as a task
require_once('../classes/task.class.php');
$task = new Task();
$task->saveMailAsTask($CustomerId, $toAddr, $bcc, $subject, $message);
// This can be used to return a success or failure
if ($mail_sent) {
redirect("http://$domainName/admin/index.php?task=account&event=viewdetails&id=$CustomerId&emailSentOK=true&d=emailResponse");
} else {
redirect("http://$domainName/admin/index.php?task=account&event=viewdetails&id=$CustomerId&emailSentOK=false&d=emailResponse");
}
I have eliminated the mailhost (localhost) as the cause of the problem, and the PHP.ini file. The only other two sources of the problem I would suppose are in the code itself and in an unknown cause that I am ignorant of. The code looks fine to me...
What gives? And why the heck can't a decent error message come out of mail()?
Some things to check:
In your php.ini ensure that sendmail_path is set to the output of
which sendmail
and then set accordingly if not:
sendmail_path = '/usr/sbin/sendmail -t'
Try send a message with sendmail and make sure you are not blacklisted:
sendmail -v someone#someaddress.com "hello"
(CTR+D will send and you can see the response from the receiving server)
The problem was the from field. I was inverting the order of the name and address.
INCORRECT:
$headers = "From: " . $this->fromAddress . " <" . $this->fromName . ">\r\n";
$headers.= "Reply-To: " . $this->fromAddress . " <" . $this->fromName . ">\r\n";
CORRECT:
$headers = "From: " . $this->fromName . " <" . $this->fromAddress . ">\r\n";
$headers.= "Reply-To: " . $this->fromName . " <" . $this->fromAddress . ">\r\n";

PHP HTML mail is not working as I wanted

I have created reset password page, where used enters hes email, and PHP sends him back a the reset key. Mail works, but its going as plain text in my gmail account. I wanted it to go in HTML.
$subject = "Your password reset for {$config['site_name']}";
$message = "<html><body>";
$message .= "<p>Someone on" . $config['site_domain'] . "tried to reset your password.</p>";
$message .= "<p>Please click below link, if you want to reset your password.</p>";
$message .= "<p><a href='" . $config['site_url'] . "/forgot_password.php?key=" . $key . "'>" . $config['site_url'] . "/forgot_password.php?key=" . $key . "</a></p>";
$message .= "<p>Thank you,<br>The Admin - " . $config['site_url'] . " </p>";
$message .= "</body></html>";
// Create email headers
// 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: Mary <mary#example.com>, Kelly <kelly#example.com>' . "\r\n";
$headers .= "From: " . $config['site_name'] . " <noreply#" . $config['site_domain'] . "> \r\n";
$headers .= "X-Sender: <noreply#" . $config['site_domain'] . "> \r\n";
$headers .= "Reply-To: <noreply#" . $config['site_domain'] . "> \r\n";
mail($input['email'],$subject,$message,$headers);
//update pw_reset field into DATABASE
$stmt = $mysqli->prepare("UPDATE members SET pw_reset = ? WHERE email = ?");
$stmt->bind_param("ss", $key, $input['email']);
$stmt->execute();
$stmt->close();
You should structure your headers like this:
$headers = 'From: You <you#example.com>' . "\n";
$headers .= 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
Notice that the From is before the MIME and Content and only Content ends with "\r\n", the other are just "\n".
Source (saganwebdesign)
Try this function. returns true on success
function sendMail($email, $subject, $message)
{
$supportEmail = 'support#abc.com';
$from = 'Test Application';
$msg = $message;
$from = str_replace(' ', '-', $from);
$frm = $from.' <'.$supportEmail.'>';
preg_match("<(.*)#(.*\..*)>", $frm, $match);
///////////////////Headers/////////////////
$hdr='';
$hdr.='MIME-Version: 1.0'."\n";
$hdr.='content-type: text/html; charset=iso-8859-1'."\n";
$hdr.="From: {$frm}\n";
$hdr.="Reply-To: {$frm}\n";
$hdr.="Message-ID: <".time()."#{$match[2]}>\n";
$hdr.='X-Mailer: PHP v'.phpversion();
$x=#mail($email, $subject, $msg, $hdr);
if($x==0)
{
$email=str_replace('#','\#', $email);
$hdr=str_replace('#','\#',$hdr);
$x=#mail($email, $subject, $msg, $hdr);
}
return $x;
}

PHP Email Formatting Issue

I am sending form data through a .swf file into this PHP page.(see below) When the email is sent, if there is an attachment the body of the message will not appear but if there is not an attachment the body appears just fine. I know that all of the variable names are correct because all of the data has been passed from the swf file. Is there something in the way I have set up the email that makes it work that way? Please let me know.
<?php
$to=$_POST['toEmail'];
$subject=$_POST['subject'];
$body = $_POST['messaggio'];
$nome = $_POST['nome'];
$email = $_POST['email'];
$attach = $_POST['attach'];
$headers = "From: $nome<" . $email . ">\n";
if ($attach == 1) {
$tmp_name = $_FILES['Filedata']['tmp_name'];
$type = $_FILES['Filedata']['type'];
$name = $_FILES['Filedata']['name'];
if(is_uploaded_file($tmp_name)){
$file = fopen($tmp_name,'rb');
$data = fread($file,filesize($tmp_name));
fclose($file);
$data = chunk_split(base64_encode($data));
$headers .= "Reply-To: <" . $email . ">\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/related; type=\"multipart/alternative\"; boundary=\"----=MIME_BOUNDARY_main_message\"\n";
$headers .= "X-Sender: $to <" . $to . ">\n";
$headers .= "Return-Path: <" . $email . ">\n";
$headers .= "This is a multi-part message in MIME format.\n";
$headers .= "------=MIME_BOUNDARY_main_message \n";
$headers .= "Content-Type: multipart/alternative; boundary=\"----=MIME_BOUNDARY_message_parts\"\n";
$message = "------=MIME_BOUNDARY_message_parts\n";
$message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\n";
$message .= "Content-Transfer-Encoding: quoted-printable\n";
$message .= "\n";
$message .= $body . "\n";
$message .= "\n";
$message .= "------=MIME_BOUNDARY_message_parts--\n";
$message .= "\n";
$message .= "------=MIME_BOUNDARY_main_message\n";
$message .= "Content-Type: application/octet-stream;\n\tname=\"" . $name . "\"\n";
$message .= "Content-Transfer-Encoding: base64\n";
$message .= "Content-Disposition: attachment;\n\tfilename=\"" . $name . "\"\n\n";
$message .= $data;
$message .= "\n";
$message .= "------=MIME_BOUNDARY_main_message--\n";
mail($to, $subject, $message, $headers);
}
} else {
if(mail($to, $subject, $body, $headers)) {
echo "ok=1";
}
}
?>
Building MIME messages, especially with attachments, is painful. You'd be better off using something like PHPMailer, which will handle the whole business for you automatically... You just have to provide the content.
Beyond that, you're slurping the attachments into memory. How big are they? Are you exceeding the script's memory_limit?

Categories