How to format email using SMTP - php

I'm trying to send formatted email with php smtp authentication, but for some reason(s) \n, \r\n and PHP_EOL can not format the message, hence everything appears on a line.
Below is what I've tried
$order .= "Title : {$title}" . PHP_EOL
."Author : {$author}" . PHP_EOL
."ISBN : {$isbn}" . PHP_EOL
."Publisher : {$publisher}" . PHP_EOL
."Supplier : {$supplier}\n
Quantity : {$qty}\r\n
The variable $order contains the body of the email.
Here is part of my sendMail() function
$from = "{$sender_name} <{$sender}>";
$to = $reciever." <$email>";
$subject = $subj;
$body = $msg;
$host = "mail.thekingsbooks.com";
$username = "noreply#thekingsbooks.com";
$password = "password";
$headers = array(
'From' => $from,
'To' => $to,
'Subject' => $subject
);
$smtp = Mail::factory(
'smtp',
array(
'host' => $host,
'auth' => true,
username => $username,
password => $password
)
);
$mail = $smtp->send($to, $headers, $body);
The sent mail looks like this
Ordered items\r\nTitle : A Retreat With Pope John Paul II: Be Not Afraid (Retreat With-- Series)\r\nAuthor : \r\nISBN : 0867164204\r\nPublisher : \r\nSupplier : \r\n\r\n Quantity : 6\r\n\r\n
Any suggestion on how to format the email body? Thanks

If you are viewing this in Outlook, Outlook may be stripping the whitespace. In Outlook, click on the option that shows the whitespace restored.

It could be that it's being sent as HTML. Trying adding "Content-type: text/plain; charset=iso-8859-1" to your headers.

Related

How to send two emails in a single contact form using PEAR Mail

I have a contact form and I want to receive message through mail and simultaneously send mail to the client. I have the below code it works some times. That is some times I get the message and client also get the message but sometimes only one email is sent either to client or to me but never both all the time.
I have seen example in the following link https://teamtreehouse.com/community/how-to-send-two-different-email-with-different-bodies-using-phpmailer but it uses PHP Mailer I want the same functionality but by using PEAR Mail.
I have seen other similar question over here PEAR Mail using gmail SMTP won't send 2 emails in sucession but the answer given in that question doesn't solve my problem
Below is the code which works some time.
<?php
require_once('Mail.php');
require_once('Mail/mime.php');
if (isset($_POST['Captcha'])) {
$name = filter_var($_POST['Name'] , FILTER_SANITIZE_STRING);
$email = filter_var($_POST['Email'] , FILTER_SANITIZE_EMAIL);
$phone = filter_var($_POST['Phone'] , FILTER_SANITIZE_STRING);
$budget = filter_var($_POST['Budget'] , FILTER_SANITIZE_STRING);
$timeline = filter_var($_POST['Timeline'] , FILTER_SANITIZE_STRING);
$description = filter_var($_POST['Description'] , FILTER_SANITIZE_STRING);
$spam = filter_var($_POST['usernameoftest'] , FILTER_SANITIZE_STRING); // Bot trap
if($spam)
{ // If the hidden field is not empty, it's a bot
die("No spamming allowed bitch!");
} else {
$from = "sales#ganeshghate.com";
$to = "ganeshghate#hotmail.com";
$subject = "Message from : ".$name;
$body = "Client's Name : ".$name."\r\n";
$body .= "Client's Email ID : ".$email."\r\n";
$body .= "Client's Phone Number : ".$phone."\r\n";
$body .= "Client's Budget : ".$budget."\r\n";
$body .= "Client's Timeline : ".$timeline."\r\n";
$body .= "Client's Message : ".$description."\r\n";
$host = "myhost";
$port = "myport";
$username = "myusername";
$password = "mypassword";
$crlf = "\n";
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
$mime = new Mail_mime($crlf);
$mime->setTXTBody($body);
$body = $mime->get();
$headers = $mime->headers($headers);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'port' => $port,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
$output["errorclientemail"] = "<div>
<h2 class='error'>".$mail->getMessage().$mail->getUserInfo()."</h2>
<h2>Oops there was some error we have not received your message</h2>
<h2>Please report the above error to us via skype , email , phone details are on the left side</h2>
</div>"."\r\n";
} else {
$output["successclientemail"] = "Thank you we will get back to you soon";
}
$bodyback = "We have received your message :".$body."\r\n";
$bodyback .= "We will get back to you soon"."\r\n";
$bodyback .= "With Regards "."\r\n";
$bodyback .= "Ganesh Ghate "."\r\n";
$subjectback = "Thank You for contacting us";
$headersreply = array ('From' => $from,
'To' => $email,
'Subject' => $subjectback);
$crlf1 = "\n";
$mime = new Mail_mime($crlf1);
$mime->setTXTBody($bodyback);
$bodyback = $mime->get();
$headersreply = $mime->headers($headersreply);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'port' => $port,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($email, $headersreply, $bodyback);
if (PEAR::isError($mail)) {
$output["errorreplyemail"] = "<div>
<h2 class='error'>".$mail->getMessage().$mail->getUserInfo()."</h2>
<h2>Oops there was some error we have not delivered confirmation email to you</h2>
<h2>Please report the above erorr to us via skype , email , phone details are on the left side</h2>
</div>"."\r\n";
} else {
$output["successreplyemail"] = "We have sent confirmation email to you. Please check your inbox / junk mail";
}
echo json_encode($output);
}
}
?>
Thanks in advance

how to send attachment with pear smtp

I want to send a file with email using pear smtp. Email is successfully going to the email. Also an attachment is going with email but with noname and no content in it. When i download the attachment it has only one line "This is a multi-part message in MIME format...".
I didn't understand whats wrong with it. I have attached the code with this question that i am using to send the attachment with email. Please guys review once and let me know what's wrong with this code.
Thanks in advance.
require_once "Mail.php";
include('Mail/mime.php');
$from = "Dispatcher <server#mymailserver.com>";
$host = "smtp.mymailserver.com";
$username = "mailuser";
$password = "password";
$to = "email#example.com";
$subject = "Subject of the email";
$hdrs = array ('From' => $from,
'To' => $to,
'Subject' => $subject,
);
$text = 'Text version of email';
$html = '<html><body>HTML version of email</body></html>';
$file = './test.txt';
$crlf = "rn";
$mime = new Mail_mime($crlf);
$mime->setTXTBody($text);
$mime->setHTMLBody($html);
$mime->addAttachment($file);
$body = $mime->get();
$hdrs = $mime->headers($hdrs);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
} else {
return 1;
}
$crlf means "carriage return, line feed" and should be that.
Use "\n" to make it work with e-mails.

Plain text email next line doesn't work even with "\r\n"

Here is my code in php mail:
<?php
include_once("Mail.php");
$From = $_POST['enquiryemail'];
$To = $row2['email'];
$Subject = "An enquiry";
$Message = "This enquiry is created by: ".$_POST['enquiryname']."\r\nOrganization: ".$row['orgname']."\r\n Telephone Number: ".$_POST['telenum']."\r\nE-mail address: ".$_POST['enquiryemail']."\r\nMessage: ".$_POST['detail'];
address: ".$_POST['enquiryemail']."\r\nMessage: ".$_POST['detail'];
$Host = "smtp.test.com";
$Username = "";
$Password = "";
$Headers = array ('From' => $From, 'To' => $To, 'Subject' => $Subject);
$SMTP = Mail::factory('smtp', array ('host' => $Host, 'auth' => false,
'username' => $Username, 'password' => $Password));
$mail = $SMTP->send($To, $Headers, $Message);
and here is the result which "\r\n" doesn't work for 2 lines in the middle:
This enquiry is created by: testing
Organization: testing Telephone Number: 123456 E-mail address: test#hotmail.com
Message: test
Any idea how to make this works? Thanks.
You need to specifically declare content type to html to use html statements
$message_string = "\r\n";
$message_string .= 'Content-Type: text/html; charset=ISO-8859-1"';
$message_string .= "\r\n";
$message_string .= $Message;
Now your break statements will take effect.
You need to <br> instead of \r\n because your content-type is text/html.
Same question here: link

PHP Html Email using Pear HTML Table and Pear Email

I am facing quite strange issue, I've php script which sends out an email to the list of users containing HTML table(with the data) and CSV attachment of the same data. The problem is when that script to send out more then 10 emails, in some of the emails we get
--=_f3be233a9b22e88524e1539166c49be0 Content-Transfer-Encoding: quoted-printable Content-Type: text/html; charset=UTF-8
in email body and HTML table lost the formatting as well, however CSV data is absolutely fine in that email.
Basically the purpose of the script is to pick the data according to user subscribe information(database-table) and send it to the subscribe user early morning. Every night the database tables are updated with the new data, which is picked up by that PHP script and send in an email. Further that PHP script trigger by Windows Schedule task.
Below is the code of the application.
if($ix>0)
{
while(odbc_fetch_row($subRes2))
{
$s_email=odbc_result($subRes2, 1);
//echo $s_email;
$from = "Sender <alerts#xxx.com>";
$to = "$s_email";
$subject = "Information_DB:" . $arrayE . " Restored on: " . "-";
$host = "xxxinternal.xxxx.com";
$port = "25";
//disabled the username and password because currently sending unauthenticated email.
// $username = ""; //<> give errors
//$password = "";
//add the email headers 29082013 1008 - SMS
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject,
'Content-Type' => 'text/html; charset=UTF-8');
$smtp = Mail::factory('smtp',
array ('host' => $host,
'port' => $port,
'auth' => false));
//'username' => $username,
//'password' => $password));
$subject = "Results from query";
$crlf = "\n";
$mime_params = array(
'text_encoding' => '7bit',
'text_charset' => 'UTF-8',
'html_charset' => 'UTF-8',
'head_charset' => 'UTF-8'
);
// Creating the Mime message
$mime = new Mail_mime($crlf);
// Setting the body of the email
//$mime->setTXTBody($body);
$mime->setHTMLBody($body);
$file='./wamp/www/' . $csv_filename;
$mime->addAttachment($csv_filename,'application/octet-stream');
$body = $mime->get($mime_params);
$headers = $mime->headers($headers);
// Sending the email
// $mail =& Mail::factory('mail');
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
// echo "<script>window.close()</script>";
}
else {
echo("<p>Message successfully sent!</p>");
}
}}}
else
{
$from = "Sender <alert#xxx.com>";
$to = "$s_email";
$subject = "Information_DB:" . $arrayE . " Restored on: " . "-";
//$host = "ssl://smtp.gmail.com";
$host = "xxxinternal.xxxx.com";
$port = "25";
//disabled the username and password because currently sending unauthenticated email.
// $username = ""; //<> give errors
//$password = "";
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject,
'Content-Type' => 'text/html; charset=UTF-8');
?>
Unfortunately when we tested I could't seen this issue. But when its went UAT lots of user get this issue and it seems to be consistent with the database. For e.g. if user A is subscribe with Spain and Russian data, then consistently they experience the issue with Russian Data email (contains the mentioned headers in the email) however Spain data email is fine. In the live its probably sending around 100's of email daily.
I will appreciate if any of you please point me out what is going wrong as I am setting up the UTF-8 character set in an email mime setup but still getting this issue.
Regards
Shoaib
Most probably you are sending emails too fast that may occur in the result of spam/unwantd email use sleep(4) to create the 4 sec delay in next `mail.
The problem was with mime type, which require to code again. Basically the message I was sending was not encoded with UTF-8 which I did. This time I user Mail_mimePart instead of Mail_mime and it works treat.
That example was very very helpful
---ahttp://tiger-fish.com/comment/reply/133---
and some of the parameter explanation for Mail_mimePart can be found on below link
ahttp://pear.php.net/manual/en/package.mail.mail-mimepart.mail-mimepart.php---
How to attach the attachment using Mail_mimePart.
ahttp://pear.php.net/manual/en/package.mail.mail-mimepart.addsubpart.php---
Hope it helps.

Encoding problem in From email and name when sending email in PHP?

What could be causing this encoding problem? Am I encoding the header information correctly or could this be caused somewhere else?
I found a similar problem here: Email from PHP has broken Subject header encoding but from what I'm reading I think I'm doing this right.
Basically sometimes our clients send emails written in french. It works but every once in a while we get some encoding issues and I'm wondering if I did the encoding wrong (I can't figure out).
$from = '=?UTF-8?B?'.base64_encode($email['from_name']).'?= <'.$email['from_email'].'>';
$to = '=?UTF-8?B?'.base64_encode($email['to_name']).'?= <'.$email['to_email'].'>';
$get_param = array(
'Content-Type' => 'text/plain;charset=utf-8',
'Content-Transfer-Encoding' => '8bit');
The code above is how I encode my header information and below is the sending:
$msg = $message_mime->get($get_param);
$headers = array (
'From' => $from,
'To' => $to,
'Reply-To' => $from,
'Subject' => utf8_decode($subject));
$headers = $message_mime->headers($headers);
$smtp = Mail::factory('smtp',
array ('host' => $smtp_settings['host'],
'auth' => true,
'username' => $smtp_settings['username'],
'password' => $smtp_settings['password']));
$mail = $smtp->send($to, $headers, $msg);
The problem is that the email they received was from:
Clientnamé de l'Ontario[=?UTF-8B?QXNzZW1ib(...)=?=]
Thanks for any help :)
Edit: The client's name basically uses the same characters as above. What I mean is that the email was supposed to be from "Clientnamé de l'Ontario"
Did you try replacing base64_encode with utf8_encode?
I'd try replacing:
$from = '=?UTF-8?B?'.base64_encode($email['from_name']).'?= <'.$email['from_email'].'>';
$to = '=?UTF-8?B?'.base64_encode($email['to_name']).'?= <'.$email['to_email'].'>';
with:
$email['from_name'] = utf8_encode($email['from_name']);
$email['to_name'] = utf8_encode($email['to_name']);
$from = $email['from_name'].' <' . $email['from_email'] . '>';
$to = $email['to_name']) . ' <' . $email['to_email'] . '>';
Might be worth a try...
Also detect_encoding could help (http://php.net/mb_detect_encoding/)?

Categories