PHP code isnt sending email [duplicate] - php

How to parse a .eml file in php? Is there any PHP libriary or PHP extension ?
I want to display the mail header information such as sender, receiver, title, attachement and eml body content in browser.

There are a couple of ways to do it. One way is to simply do it yourself, it's not that complicated.
Otherwise, you might want to have a look at the Mailparse library:
http://php.net/manual/en/book.mailparse.php
And there is also this one:
http://code.google.com/p/php-mime-mail-parser/

This is what I use:
composer require php-mime-mail-parser/php-mime-mail-parser
And then PHP:
$parser = new \PhpMimeMailParser\Parser();
$emailFile = 'myEmailFile.eml';
$parser->setText(file_get_contents($emailFile));
Then, to get addresses:
$toAddressesQ = $parser->getAddresses('to');
Or the body:
$text = $parser->getMessageBody('text');
$html = $parser->getMessageBody('html');
Or the header:
$subject = $parser->getHeader('subject');
Or the attachments:
$attachments = $parser->getAttachments();

Related

How to send message a list with foreach only one message

I am trying to send a message with one list with PHP, here is my code:
$packs = $db->QueryFetchArrayAll("SELECT * FROM configmoreg");
foreach($packs as $pack) {
echo '<a>'.$pack['setting_id'].'</a>
<a>'.$pack['config_name'].'</a>
<a>'.$pack['config_value'].'</a>
<br>';
}
mail('example#something.com',"My List",$msg);
How do I make it send only one message with list on it?
For example:
id 00000001
My_name game_over_new
NR_Job 11
type_secure MD5
5 etc...
Build up a string in the for-loop, and send that. Consider:
$msg = '';
foreach($packs as $pack)
$msg .= "<a>${pack['some_key']}</a>";
$subject = "My List";
mail('null#example.com', $subject, $msg);
Meanwhile, I gather you're still learning PHP, so hold on to this next piece of advice until you're ready: don't use PHP's builtin mail() function, use PHPMailer.
Try adding all the variables to an array; then send the array containing the variables.
As you don't know how to use arrays I suggest reading:
https://www.w3schools.com/php/php_arrays.asp
However to get what you want, you'll want something along these lines:
$infoToSend = array($pack['setting_id'], $pack['config_name'], $pack['config_value']);
mail('example#something.com',"My List", $infoToSend);

duplicate empty messages in php imap?

I am fetching mail messages in php via imap.
Its working well to retrieve the email header and body however frequently some of the messages seem to be coming through twice, the only difference being that in that duplicate the email BODY is empty - all that exists are the email headers.
I have added logging and it seems that the EMPTY message normally comes through first and then on subsequent fetches the full message is retrieved.
Can anyone explain this to me? Is there any reason why retrieving messages from imap will first return empty body emails in SOME but not all cases?
This is my code that is fetching the emails.
$messages = imap_sort($imap, SORTARRIVAL, $sortorder,0,$searchval);
foreach ($messages as $message) {
$header = imap_header($imap, $message);
//Get user from reply-to header info
$useremail = "{$header->reply_to[0]->mailbox}#{$header->reply_to[0]->host}";
$userfullname = $header->reply_to[0]->personal;
//get subject from header
$subject = $header->subject;
$fh = imap_fetchheader($imap, $message);
$fb = imap_body($imap, $message);
$fullbody = $fh.$fb;
// GET TEXT BODY
$bodyTxt = get_part($imap, $message, "TEXT/PLAIN");
//GET HTML BODY
$bodyHtml = get_part($imap, $message, "TEXT/HTML");
In many cases the first time the message is retrieved it will have an empty body (ie $fullbody will be empty). Often this comes in batches for eg 10 messages will be logged as having empty body.
Subsequently the same batch is then retrieved but this time with a body - and I have no explanation for it.
Can anyone offer any ideas?
Thanks

PHP change string parsed from email

Using a PHP script file to filter emails. Everything is working properly, but it seems that if I were to initiate a conversation between a cell phone (Verizon Wireless) and the SMTP server, Verizon changes the format of outgoing messages.
For example, I need to respond to an email using XXX#vtext.com but Verizon will respond with XXX#vzwpix.com which cannot be responded to. So I created the following code to try and remove and replace the #vzwpix.com but it still isn't sending the mail. I know the code is working however because if I change the $from in the mail function to XXX#vtext.com the code works and sends the message.
//Parse "from"
$from1 = explode ("\nFrom: ", $email);
$from2 = explode ("\n", $from1[1]);
if(strpos ($from2[0], '<') !== false)
{
$from3 = explode ('<', $from2[0]);
$from4 = explode ('>', $from3[1]);
$from = $from4[0];
}
else
{
$from = $from2[0];
}
if(strpos ($from[1], '#vzwpix.com') !== false) {
str_replace('#vzwpix.com', '#vtext.com', $from);
}
var_dump( mail( $from, "Hi", "What is the email:"));
I am using var_dump just for developmental purposes by the way.
I did some research and I think the best way to do this maybe is to explode the XXX#vzwpix.com at the # symbol, then run a str_replace('vzwpix.com','vtext.com', $from5); However, that didn't work and then I thought maybe implode it after running a str_replace?
If the bad domains are static, why don't you explode on 'vzwpix' and then implode on 'vtext'? This should replace each of the bad instances in you address string.
You forgot to get the result of your str_replace
$from_with_vtext=str_replace('#vzwpix.com', '#vtext.com', $from[1]);

Unable to Parse JSON Fields Due to Leading Bracket in PHP

I'm trying to create a webhook for Mandrill that will send an e-mail to the sender when a previously sent e-mail bounces. I'm able to receive the JSON data from Mandrill, but am unable to parse that data to send to the original sender:
<?php
require_once 'mandrill-api-php/src/Mandrill.php'; //Not required with Composer
$mandrill = new Mandrill('*myapikey*');
$json = stripslashes($_POST['mandrill_events']);
$jsondata = json_decode($json,true);
$subject = $jsondata['event'];
$message = "STRIPSLASHES: ".$json."----JSONDATA----".$jsondata;
$emailAddress = "*me#mydomain.com*";
mail($emailAddress, $subject, $message);
?>
Here is what the $json data looks like in the $message variable. It is a literal copy and paste from the test e-mail I receive:
STRIPSLASHES: [{"event":"spam","msg":{"ts":1365109999,"subject":"This an example webhook message","email":"example.webhook#mandrillapp.com","sender":"example.sender#mandrillapp.com","tags":["webhook-example"],"opens":[{"ts":1365111111}],"clicks":[{"ts":1365111111,"url":"http://mandrill.com"}],"state":"sent","metadata":{"user_id":111},"_id":"exampleaaaaaaaaaaaaaaaaaaaaaaaaa","_version":"exampleaaaaaaaaaaaaaaa"},"_id":"exampleaaaaaaaaaaaaaaaaaaaaaaaaa","ts":1422475458},{"event":"spam","msg":{"ts":1365109999,"subject":"This an example webhook message","email":"example.webhook#mandrillapp.com","sender":"example.sender#mandrillapp.com","tags":["webhook-example"],"opens":[{"ts":1365111111}],"clicks":[{"ts":1365111111,"url":"http://mandrill.com"}],"state":"sent","metadata":{"user_id":111},"_id":"exampleaaaaaaaaaaaaaaaaaaaaaaaaa1","_version":"exampleaaaaaaaaaaaaaaa"},"_id":"exampleaaaaaaaaaaaaaaaaaaaaaaaaa1","ts":1422475458}]----JSONDATA----Array
I notice that the $json is outputting the json data, but has a leading and ending bracket, as opposed to starting with a squiggly bracket. So I decided to call the data as if it were an array, but to no avail.
In a test, instead of doing $json = stripslashes(... I copy and pasted the json data above as a literal string. Once I removed the leading/ending brackets, I was able to parse some data.
Why don't you try removing the brackets using PHP?
$json = ltrim($json, "[");
$json = rtrim($json, ']");
And then pass it to the decoder?
Actually, I was able to fix it by "grabbing" the json data a different way, formatting it correctly as I receive it:
$rawdata = file_get_contents('php://input');
$decodeurl = urldecode($data);
$jsonready = substr($decodeurl, 16);
$data = json_decode($jsonready, true);
$recipient = $data['0']['msg']['email'];
//etc, etc, etc
I followed this example:
https://sendy.co/forum/discussion/1137/using-mandrill-webhook-for-bounces-complaints/p1
I hope this helps people who are trying to utilize Mandrill's API!

load html mail file inside php

I implemented a html email inside a html file. And i have a php file which uses the PHPMailer class to send emails.
What i want to achieve is, i have some text inside the html that should change depends who i send the email.
This is the php file that sends the emails
<?php
// get variables
$contact_name = addslashes($_GET['contact_name']);
$contact_phone = addslashes($_GET['contact_phone']);
$contact_email = addslashes($_GET['contact_email']);
$contact_message = addslashes($_GET['contact_message']);
// send mail
require("class.phpmailer.php");
$mailer = new PHPMailer();
$mailer->IsSMTP();
$mailer->Host = 'ssl://smtp.gmail.com:465';
$mailer->SMTPAuth = TRUE;
$mailer->Username = 'danyel.p#gmail.com';
$mailer->Password = 'mypass';
$mailer->From = 'contact_email';
$mailer->FromName = 'PS Contact';
$mailer->Subject = $contact_name;
$mailer->AddAddress('pdaniel#gmail.com');
$mailer->Body = $contact_message;
if($mailer->Send())
echo 'ok';
?>
And the html file containing a simple html mail implemented with tables and all that standard it need.
I want to ask braver minds than mine which is the best approach to accomplish this. :)
Thank you in advance,
Daniel!
EDIT: right now, in the $mailer->Body i have the $contact_message variable as a text email.. but i want in that body to load an html file containing an html email and i want to somehow change the body of the html email with the text inside this $contact_message variable.
One simple way to go is to have special tokens in your html files that will be replaced by the caller. For example assuming that you have two variables that might dynamically change content, name, surname then put something like this in your html: %%NAME%%, %%SURNAME%% and then in the calling script simply:
$html = str_replace("%%NAME%%", $name, $html);
$html = str_replace("%%SURNAME%%", $surname, $html);
or by nesting the two above:
$html = str_replace("%%NAME%%", $name, str_replace("%%SURNAME%%", $surname, $html));
EDIT
A more elegant solution in case you have many variables: Define an associative array that will hold your needles and replacements for them:
$myReplacements = array ( "%%NAME%%" => $name,
"%%SURNAME%%" => $surname
);
and use a loop to make it happen:
foreach ($myReplacements as $needle => $replacement)
$html = str_replace($needle, $replacement, $html);
Create conditional statements based on the email you want to see to.
Then include that in the tempalted php html email text.
You can also pass the changing values to a function which will implement the above.
If I build a website I usually use a templating engine, something like Smarty... You could write your html mail in a smarty template file. Then you could add the wanted texts based on criteria automatically. Just assign the correct values to the templating engine.
To answer your edit:
function renderHtmlEmail($body) {
ob_start();
include ('my_html_email.php');
return ob_get_clean();
}
In your my_html_email.php file you would have something like so:
<html>
<body>
<p>....<p>
<!-- the body -->
<?php echo $body; ?>
</body>
</html>
And
$mailer->Body = renderHtmlEmail($contact_message);
If you need other variables to pass to the layout/template file, add params to that method, or pass an associative array like so function renderHtmlEmail($viewVars) and inside the function extract($viewVars);
You will then be able to use those vars inside the template, for ex. Dear <?php echo $to; ?>,
You will probably have to change your html file from .html to .php if it isn't already.
That is, if I understood the issue correctly.

Categories