Broken links inside PHP emailer with AngularJS - php

I have an AngularJS app that sends emails using a PHP document.
The email body includes two links to images that are populated with a JS variables.
Most of the emails arrive good and the links work, but in some of them, the links (both or one of them) will come out broken, looking like this:
https://blabla.com/register/uploads/Frankfurt2018-22-03-2018-16-07-52.!
Or like this:
https://blabla.com/register/uploads/KoelnerListe2%21
Or like this:
https://blabla.com/register/upload!
It's weird cause sometimes is both links, sometimes is only one, and most of the times are correct.
The link variable comes from the Angular app and looks like this:
$scope.sendapplication = function(){
$scope.photoor = "https://blabla.com/register/uploads/"+$scope.photoor;
$scope.photosmall = "https://blabla.com/register/uploads/"+$scope.photo;
$scope.exhibitor = {
'img':$scope.photosmall,
'imgoriginal':$scope.photoor,
};
var $promise=$http.post('emailtest.php',$scope.exhibitor);
$promise.then(function (data) {
...
});
};
And in the php file I do this:
$contentType = explode(';', $_SERVER['CONTENT_TYPE']); // Check all available Content-Type
$rawBody = file_get_contents("php://input"); // Read body
$data = array(); // Initialize default data array
if(in_array('application/json', $contentType)) {
$data = json_decode($rawBody); // Then decode it
$photo = $data->img;
$photooriginal = $data->imgoriginal;
} else {
parse_str($data, $data); // If not JSON, just do same as PHP default method
}
header('Content-Type: application/json; charset=UTF-8');
echo json_encode(array( // Return data
'data' => $data
));
$sabine = 'blabla#gmail.com';
$headerss = "From: ".$galleryname."<".$email.">\r\nReturn-path: ".$email."";
$headerss .= "Reply-To: ".$galleryname."<".$email.">";
$headerss .= "MIME-Version: 1.0\r\n";
$headerss .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$recipient = $sabine;
$subjects = "Registration for ".$fairumlaut." - ".$galleryname."";
$bodys .= "<p><strong>Original photo</strong>: Link</p>";
$bodys .= "<p><strong>Web resized photo</strong>: Link</p>";
$bodys .= "<p></p>";
mail($recipient, $subjects, $bodys, $headerss);
What could cause such weird behaviour?

wrap the link in urlencode function. This will solve your issue.
update: or if I read your code I would have seen that the links are coming from JS. Try encodeURI().. ;)

Related

PHP to store all variables from loop to use them later

I am trying to use some WSDL webservice to do some work with each parameters. This is working absolutely fine; however, once the script is executed, I would like to have "log" emailed to me.
All works fine when I use PRINT, or ECHO inside the loop (this will display all values of different variables from the loop). However, outside of the loop, this will only display ONE variable.
Is there a way to store all variables into array inside of loop so this can be used later on, outside of loop, for example emailing this?
This is what I have tried:
<?php
// API request and response
$requestParams = array(
'Request' => 'Hello'
);
$client = new SoapClient('https://example.com/webservice.asmx?WSDL');
$response = $client->Command($requestParams);
//Load response as XML
$xml = simplexml_load_string($response);
$rows = $xml->children('rs', TRUE)->data->children('z', TRUE)->row;
foreach ($rows as $row) {
$attributes = $row->attributes();
/* XML document contains two columns, first with attribute TO,
second with attribute Ref. This will extract required data */
$To = (string) $attributes->To;
$Ref= (string) $attributes->Ref;
// Here are few more lines in code to do some other work with each variable
// All works absolutely fine until this line
/* I would liket to store all variables so I can use them to email
them as a log in one email */
$ToLog .= "<br>$To</br>";
$RefLog .="<br>$Ref</br>";
}
$to = "nobody#example.com";
$subject = "Script successfully executed";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$message = $ToLog . $RefLog
mail($to, $subject, $message, $headers);
?>
I think you just need to define both variable before starting the loop, like:
$ToLog = "";
$RefLog = "";
Then if you can put whatever in this variable in side the loop you will get it after the loop, You do not need to take an array.
You do not need to take an array.
try like this
$values = array();
foreach ($rows as $row) {
$values[] = $row->attributes(); //stores the each values to the array
}
print_r($values);
Try something like this
$finalArray = array();
foreach($rows as $row)
{
$finalArray[] = $row["someIndex"];
}
then finalArray should contains all variables from foreach :)

my CSV attachment is empty! PHP [duplicate]

This question already has an answer here:
PHP attachment in email is empty
(1 answer)
Closed 9 years ago.
Im trying to take data from the database and display it in a CSV file which is both downloadable and emailed to someone. I have managed to get the downloadable file working and it displays all of the correct data. It also sends a CSV file to the necessary person but that CSV file is empty and no data is displayed in it.
Here is my code:
$myroot = "../../";
include($myroot . "inc/functions.php");
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=surveys.csv');
$output = fopen('php://output', 'w');
// Create CSV file
fputcsv($output, array('Name', 'Branch', 'Website','Company', 'Question1', 'Question2', 'Question3', 'Question4', 'Question5'));
$mysql_connection = db_connect_enhanced('*****','*****','*****','*****');
$query='SELECT * FROM *****.*****';
$surveys = db_query_into_array_enhanced($mysql_connection, $query);
$count = count($surveys);
$data = array();
for($i=0; $i<=$count; $i++){
$data[] = array($surveys[$i]['FeedbackName'], $surveys[$i]['BranchName'], $surveys[$i]['FeedbackWebsite'], $surveys[$i]['FeedbackCompany'], $surveys[$i]['Question1'], $surveys[$i]['Question2'], $surveys[$i]['Question3'], $surveys[$i]['Question4'], $surveys[$i]['Question5']);
}
foreach( $data as $row )
{
fputcsv($output, $row, ',', '"');
}
fclose($output);
$encoded = chunk_split(base64_encode($output));
// create the email and send it off
$subject = "File you requested from RRWH.com";
$from = "*****#*****.com";
$headers = 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-Type: multipart/mixed;
boundary="----=_NextPart_001_0011_1234ABCD.4321FDAC"' . "\n";
$message = '
This is a multi-part message in MIME format.
------=_NextPart_001_0011_1234ABCD.4321FDAC
Content-Type: text/plain;
charset="us-ascii"
Content-Transfer-Encoding: 7bit
Hello
We have attached for you the PHP script that you requested from http://rrwh.com/scripts.php
as a zip file.
Regards
------=_NextPart_001_0011_1234ABCD.4321FDAC
Content-Type: application/octet-stream; name="';
$message .= "surveys.csv";
$message .= '"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="';
$message .= "surveys.csv";
$message .= '"
';
$message .= $encoded;
$message .= '
------=_NextPart_001_0011_1234ABCD.4321FDAC--
';
mail("*****#*****.com", $subject, $message, $headers, "-f$from");
I've spent a day and a half on this but I cant see the problem. Could someone please point it out to me as to why the attached CSV file is empty?
i'm getting kind of desperate and stressed out :( please someone help me.
base64_encode() expects the parameter to be a string and you give it a (closed) resource.
Try to read the resource into a string, or use file_get_contents or build your string while you write into the resource.
Update:
Try and replace
foreach( $data as $row )
{
fputcsv($output, $row, ',', '"');
}
fclose($output);
$encoded = chunk_split(base64_encode($output));
by
$myoutput = '"Name","Branch","Website","Company","Question1","Question2","Question3","Question4","Question5"';
foreach( $data as $row )
{
$myoutput .= "\"".implode('","',$row)."\"\n";
fputcsv($output, $row, ',', '"');
}
fclose($output);
$encoded = chunk_split(base64_encode($myoutput));
This way, everything you write into your output you also write into a new variable ($myoutput). Since this is a string you can use it with base64_encode().

Accessing JSON object via PHP

I have the following code..
if (config.sendResultsURL !== null)
{
console.log("Send Results");
var collate =[];
for (r=0;r<userAnswers.length;r++)
{
collate.push('{"questionNumber'+parseInt(r+1)+ '"' + ': [{"UserAnswer":"'+userAnswers[r]+'", "actualAnswer":"'+answers[r]+'"}]}');
}
$.ajax({
type: 'POST',
url: config.sendResultsURL,
data: '[' + collate.join(",") + ']',
complete: function()
{
console.log("Results sent");
}
});
}
Using Firebug I get this from the console.
[{"questionNumber1": [{"UserAnswer":"3", "actualAnswer":"2"}]},{"questionNumber2": [{"UserAnswer":"3", "actualAnswer":"2"}]},{"questionNumber3": [{"UserAnswer":"3", "actualAnswer":"2"}]},{"questionNumber4": [{"UserAnswer":"3", "actualAnswer":"1"}]},{"questionNumber5": [{"UserAnswer":"3", "actualAnswer":"1"}]}]
From here the script sends data to emailData.php which reads...
$json = json_decode($_POST, TRUE);
$body = "$json";
$to = "myemail#email.com";
$email = 'Diesel John';
$subject = 'Results';
$headers = "From: $email\r\n";
$headers .= "Content-type: text/html\r\n";
// Send the email:
$sendMail = mail($to, $subject, $body, $headers);
Now I do get the email however it is blank.
My question is how do I pass the data to emailData.php and from there access it?
Create an object that you want to pass to PHP
Use JSON.stringify() to make a JSON string for that object.
Pass it to PHP script using POST or GET and with a name.
Depending on your request capture it from $_GET['name'] OR $_POST['name'].
Apply json_decode in php to get the JSON as native object.
In your case you can just pass userAnswers[r] and answers[r]. Array sequence are preserved.
In for loop use,
collate.push({"UserAnswer":userAnswers[r], "actualAnswer":answers[r]});
In ajax request use,
data: {"data" : JSON.stringify(collate)}
In the PHP end,
$json = json_decode($_POST['data'], TRUE); // the result will be an array.
json_decode converting string to object.
just do bellow code and check the values.
print_r($json)
Directly assign json object to string this is very bad.
If you decode your json, you will have a hash and not a string. If you want to be mailed the same as what you printed on the console, simply do this:
$body = $_POST['data'];
Another option would be to parse json into a php hash and var_dump that:
$json = json_decode($_POST['data'], TRUE);
$body = var_export($json, TRUE);
Using below JavaScript code
var collate =[], key, value;
for (r=0;r<userAnswers.length;r++) {
key = questionNumber + parseInt(r+1);
value = { "UserAnswer": userAnswers[r], "actualAnswer": answers[r] };
collate.push({ key : value });
}
$.post( config.sendResultsURL, { data: collate }, function(data) {
console.log("Results sent");
});
And do this in PHP
$data = json_decode( $_POST['data'], true );
and you will have all your data with array.
$jsonData = file_get_contents('php://input');
$json = json_decode($jsonData, 1);
mail('email', 'subject', print_r($json, 1));

Has anyone created an ics iCalendar generator function that works with Google Calendar?

I'm trying to generate an .ics file that imports successfully into Google calendar. Google Calendar is proving especially difficult (I've got Outlook and Apple iCal working perfectly).
Does anyone have a php function or class which creates the right headers and inserts events that's been proven to work with Google calendar?
I also see this is an older post, but with no accepted answer.
Recently, I needed to implement ical generation into my web app... but mine also required recurring events with a given formula. For this, I used a combination of the following packages:
For ical generation: https://github.com/markuspoerschke/iCal
For recurring events: https://github.com/simshaun/recurr
I use recurr to generate a list of dates based on a recurrence formula:
public function generate_dates_array(\DateTime $end_date = null) : array
{
if(! $end_date) {
$end_date = new \DateTime('midnight');
}
$rule = new \Recurr\Rule($this->recurrence_rule, $this->created_at->setTime(0,0));
$rule->setUntil($end_date);
$transformer = new ArrayTransformer();
$dates = $transformer->transform($rule);
$dateArray = [];
foreach($dates as $date) {
$dateArray[] = $date->getStart();
}
return $dateArray;
}
Then setup my calendar:
$vCalendar = new \Eluceo\iCal\Component\Calendar('YourUrlHere');
$vCalendar->setName('YOUR NAME HERE');
$vCalendar->setDescription('YOUR DESCRIPTION HERE');
Then loop over those dates adding events to my calendar object... making sure to adjust my times to UTC from the user's chosen timezone.
$today = new Carbon();
$end_date = $today->addMonth();
foreach($events as $event) {
$dates = $event->generate_dates_array($end_date); // function shown in above code snippet
$duration = $event->duration ? $event->duration : 30;
// Each Occurrence for event
foreach($dates as $date) {
$vEvent = new \Eluceo\iCal\Component\Event();
$date_string = "{$date->format('Y-m-d')} {$event->time}";
$start_time = new Carbon($date_string, $user->time_zone);
$start_time->setTimezone('UTC');
$vEvent->setDtStart($start_time);
$end_time = new Carbon($date_string, $user->time_zone);
$end_time = $end_time->addMinutes($duration);
$end_time->setTimezone('UTC');
$vEvent->setDtEnd($end_time);
$vEvent->setNoTime(false);
$vEvent->setSummary($event->name);
$vEvent->setDescription("$event->description");
$vCalendar->addComponent($vEvent);
}
}
After everything is setup properly, I output the calendar. This means I can use the URL that generates this file to import the calendar into Google Calendar (or any other calendar program) and it'll ping it daily for updates. (URL must be publicly accessibly, which required I used a guid as the identifier instead of user_id, by the way)
header('Content-Type: text/calendar; charset=utf-8');
echo $vCalendar->render();
Hopefully this helps anyone else landing here!
This is an old one, and the only answer wasn't accepted, so not sure if the below code fixed your issue. However, I came across this in my own searches to try to fix a bug I had, and now that I have a solution, I figured I would share it. The below code has been tested with the latest Outlook and with Gmail.
With outlook what was causing my bug was that I was using \n instead of \r\n for the event details. So, as you'll see below, I use \r\n for the event and \n for everythign else so that PHP processes it correctly. Perhaps a similar problem was causing the issues with gmail?
Warning, this code does nothing to prevent header injection, please
use responsibly ;-)
<?php
date_default_timezone_set('America/New_York');
//CONFIGURE HERE
$fromName = "John Doe";
$fromEmail = "john.doe#example.com";
$toName = "Your Name";
$toEmail = 'yourname#example.com';
$start = new DateTime('2017-08-15 15:00');
$end = new DateTime('2017-08-15 16:00');
$summary = "Hello World Event";
//END CONFIGURATION
$uid = "0123456789";
$headers = array();
$boundary = "_CAL_" . uniqid("B",true) . "_B_";
$headers[] = "MIME-Version: 1.0";
$headers[] = "Content-Type: multipart/alternative; boundary=\"".$boundary."\"";
$headers[] = "To: \"{$toName}\" <{$toEmail}>";
$headers[] = "From: \"{$fromName}\" <{$fromEmail}>";
$calendarLines = array(
"BEGIN:VCALENDAR",
"METHOD:REQUEST",
"PRODID:-//PHP//MeetingRequest//EN",
"VERSION:2.0",
"BEGIN:VEVENT",
"ORGANIZER;CN={$fromName}:MAILTO:{$fromEmail}",
"ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;CN={$toName}:MAILTO:{$toEmail}",
"DESCRIPTION:{$summary}",
"SUMMARY:{$summary}",
"DTSTART:".$start->setTimezone(new DateTimeZone('UTC'))->format('Ymd\THis\Z'),
"DTEND:".$end->setTimezone(new DateTimeZone('UTC'))->format('Ymd\THis\Z'),
"UID:{$uid}",
"CLASS:PUBLIC",
"PRIORITY:5",
"DTSTAMP:".gmdate('Ymd\THis\Z'),
"TRANSP:OPAQUE",
"STATUS:CONFIRMED",
"SEQUENCE:0",
"LOCATION:123 Any Street",
"BEGIN:VALARM",
"ACTION:DISPLAY",
"DESCRIPTION:REMINDER",
"TRIGGER;RELATED=START:-PT15M",
"END:VALARM",
"END:VEVENT",
"END:VCALENDAR"
);
$calendarBase64 = base64_encode(implode("\r\n",$calendarLines));
//ensure we don't have lines longer than 70 characters for older computers:
$calendarResult = wordwrap($calendarBase64,68,"\n",true);
$emailLines = array(
"--{$boundary}",
"Content-Type: text/html; charset=\"iso - 8859 - 1\"",
"Content-Transfer-Encoding: quoted-printable",
"",
"<html><body>",
"<h1>Hello World</h1>",
"<p>This is a calendar event test</p>",
"</body></html>",
"",
"--{$boundary}",
"Content-Type: text/calendar; charset=\"utf - 8\"; method=REQUEST",
"Content-Transfer-Encoding: base64",
"",
$calendarResult,
"",
"--{$boundary}--"
);
$emailContent = implode("\n",$emailLines);
$headersResult = implode("\n",$headers);
mail($toEmail, $summary, $emailContent, $headersResult );
echo("<pre>".htmlentities($headersResult)."\n\n".htmlentities($emailContent)."</pre>");
echo("<br /><br />");
echo("<pre>".base64_decode($calendarResult)."</pre>");
I have done a similar thing but just created a URL instead of an iCal.
Check out https://support.google.com/calendar/answer/3033039
Fill out the form and generate HTML then in the php file I was using to create the ical i just created a separate thing to replace the details with variables.
EG:
if($calType === "iCal"){
//set correct content-type-header
header('Content-Disposition: attachment; filename=AddToCalendar.ics');
header('Content-Type: text/calendar; charset=utf-8');
$desc = str_replace("\n", '\n', $desc);
$desc = str_replace(array("\r","\n","\r"), '', $desc);
$ical = "BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Smartershows.com//TheBatteryShow//EN
X-WR-CALNAME;CHARSET=utf-8:".$subj."
METHOD:PUBLISH
X-MS-OLK-FORCEINSPECTOROPEN:TRUE
BEGIN:VEVENT
SUMMARY;CHARSET=utf-8:".$subj."
LOCATION;CHARSET=utf-8:".$loc."
URL:".$url."
UID:30fc985de98ed0dabfeb13722e3c82259fcd33e3
DESCRIPTION:".$desc."
DTSTART:".$sDate."T".$sTime."
DTEND:".$eDate."T".$eTime."
END:VEVENT
END:VCALENDAR";
return $ical;
exit;
}else if($calType === "gCal"){
$href = "http://www.google.com/calendar/event?";
$href .= "action=TEMPLATE";
$href .= "&text=".urlencode($subj);
$href .= "&dates=".$sDate."T".$sTime."/".$eDate."T".$eTime;
$href .= "&details=".urlencode($desc);
$href .= "&location=".urlencode($loc);
$href .= "&trp=false";
$href .= "&sprop=".urlencode($subj);
$href .= "&sprop=name:".urlencode($url);
return '<strong>Download for Gmail</strong>';
}
So the first block in the if is making the ical and the second is taking the same info to build a url that google will take and populate a calendar page.
The downside of this though is that you can only put basic things into the description...not a lot of fancy html or anything...unless you htmlencode everything i guess but even then im not sure what the character limit of a url is...
Hotmail and Yahoo mail can both populate calendars this way as well but unfortunately neither have a nice tool (that i can find) that generates a link beforehand that you can use.
Hope this helps!

Send Mail from raw body for testing purposes

I am developing a PHP application that needs to retrieve arbitrary emails from an email server. Then, the message is completely parsed and stored in a database.
Of course, I have to do a lot of tests as this task is not really trivial with all that different mail formats under the sun. Therefore I started to "collect" emails from certain clients and with different contents.
I would like to have a script so that I can send out those emails automatically to my application to test the mail handling.
Therefore, I need a way to send the raw emails - so that the structure is exactly the same as they would come from the respective client. I have the emails stored as .eml files.
Does somebody know how to send emails by supplying the raw body?
Edit:
To be more specific: I am searching for a way to send out multipart emails by using their source code. For example I would like to be able to use something like that (an email with plain and HTML part, HTML part has one inline attachment).
--Apple-Mail-159-396126150
Content-Transfer-Encoding: quoted-printable
Content-Type: text/plain;
The plain text email!
--=20
=20
=20
--Apple-Mail-159-396126150
Content-Type: multipart/related;
type="text/html";
boundary=Apple-Mail-160-396126150
--Apple-Mail-160-396126150
Content-Transfer-Encoding: quoted-printable
Content-Type: text/html;
charset=iso-8859-1
<html><head>
<title>Daisies</title>=20
</head><body style=3D"background-attachment: initial; background-origin: =
initial; background-image: =
url(cid:4BFF075A-09D1-4118-9AE5-2DA8295BDF33/bg_pattern.jpg); =
background-position: 50% 0px; ">
[ - snip - the html email content ]
</body></html>=
--Apple-Mail-160-396126150
Content-Transfer-Encoding: base64
Content-Disposition: inline;
filename=bg_pattern.jpg
Content-Type: image/jpg;
x-apple-mail-type=stationery;
name="bg_pattern.jpg"
Content-Id: <4BFF075A-09D1-4118-9AE5-2DA8295BDF33/tbg.jpg>
/9j/4AAQSkZJRgABAgAAZABkAAD/7AARRHVja3kAAQAEAAAASAAA/+IFOElDQ19QUk9GSUxFAAEB
[ - snip - the image content ]
nU4IGsoTr47IczxmCMvPypi6XZOWKYz/AB42mcaD/9k=
--Apple-Mail-159-396126150--
Using PHPMailer, you can set the body of a message directly:
$mail->Body = 'the contents of one of your .eml files here'
If your mails contain any mime attachments, this will most likely not work properly, as some of the MIME stuff has to go into the mail's headers. You'd have to massage the .eml to extract those particular headers and add them to the PHPMailer mail as a customheader
You could just use the telnet program to send those emails:
$ telnet <host> <port> // execute telnet
HELO my.domain.com // enter HELO command
MAIL FROM: sender#address.com // enter MAIL FROM command
RCPT TO: recipient#address.com // enter RCPT TO command
<past here, without adding a newline> // enter the raw content of the message
[ctrl]+d // hit [ctrl] and d simultaneously to end the message
If you really want to do this in PHP, you can use fsockopen() or stream_socket_client() family. Basically you do the same thing: talking to the mailserver directly.
// open connection
$stream = #stream_socket_client($host . ':' . $port);
// write HELO command
fwrite($stream, "HELO my.domain.com\r\n");
// read response
$data = '';
while (!feof($stream)) {
$data += fgets($stream, 1024);
}
// repeat for other steps
// ...
// close connection
fclose($stream);
You can just use the build in PHP function mail for it. The body part doesnt have to be just text, it can also contain mixed part data.
Keep in mind that this is a proof of concept. The sendEmlFile function could use some more checking, like "Does the file exists" and "Does it have a boundry set". As you mentioned it is for testing/development, I have not included it.
<?php
function sendmail($body,$subject,$to, $boundry='') {
define ("CRLF", "\r\n");
//basic settings
$from = "Example mail<info#example.com>";
//define headers
$sHeaders = "From: ".$from.CRLF;
$sHeaders .= "X-Mailer: PHP/".phpversion().CRLF;
$sHeaders .= "MIME-Version: 1.0".CRLF;
//if you supply a boundry, it will be send with your own data
//else it will be send as regular html email
if (strlen($boundry)>0)
$sHeaders .= "Content-Type: multipart/mixed; boundary=\"".$boundry."\"".CRLF;
else
{
$sHeaders .= "Content-type: text/html;".CRLF."\tcharset=\"iso-8859-1\"".CRLF;
$sHeaders .= "Content-Transfer-Encoding: 7bit".CRLF."Content-Disposition: inline";
}
mail($to,$subject,$body,$sHeaders);
}
function sendEmlFile($subject, $to, $filename) {
$body = file_get_contents($filename);
//get first line "--Apple-Mail-159-396126150"
$boundry = $str = strtok($body, "\n");
sendmail($body,$subject,$to, $boundry);
}
?>
Update:
After some more testing I found that all .eml files are different. There might be a standard, but I had tons of options when exporting to .eml. I had to use a seperate tool to create the file, because you cannot save to .eml by default using outlook.
You can download an example of the mail script. It contains two versions.
The simple version has two files, one is the index.php file that sends the test.eml file. This is just a file where i pasted in the example code you posted in your question.
The advanced version sends an email using an actual .eml file I created. it will get the required headers from the file it self. Keep in mind that this also sets the To and From part of the mail, so change it to match your own/server settings.
The advanced code works like this:
<?php
function sendEmlFile($filename) {
//define a clear line
define ("CRLF", "\r\n");
//eml content to array.
$file = file($filename);
//var to store the headers
$headers = "";
$to = "";
$subject = "";
//loop trough each line
//the first part are the headers, until you reach a white line
while(true) {
//get the first line and remove it from the file
$line = array_shift($file);
if (strlen(trim($line))==0) {
//headers are complete
break;
}
//is it the To header
if (substr(strtolower($line), 0,3)=="to:") {
$to = trim(substr($line, 3));
continue;
}
//Is it the subject header
if (substr(strtolower($line), 0,8)=="subject:") {
$subject = trim(substr($line, 8));
continue;
}
$headers .= $line . CRLF;
}
//implode the remaining content into the body and trim it, incase the headers where seperated with multiple white lines
$body = trim(implode('', $file));
//echo content for debugging
/*
echo $headers;
echo '<hr>';
echo $to;
echo '<hr>';
echo $subject;
echo '<hr>';
echo $body;
*/
//send the email
mail($to,$subject,$body,$headers);
}
//initiate a test with the test file
sendEmlFile("Test.eml");
?>
You could start here
http://www.dreamincode.net/forums/topic/36108-send-emails-using-php-smtp-direct/
I have no idea how good that code is, but it would make a starting point.
What you are doing is connecting direct to port 25 on the remote machine, as you would with telnet, and issuing smtp commands. See eg http://www.yuki-onna.co.uk/email/smtp.html for what's going on (or see Jasper N. Brouwer's answer).
Just make a quick shell script which processes a directory and call it when you want e.g. using at crontab etc
for I in ls /mydir/ do cat I | awk .. | sendmail -options
http://www.manpagez.com/man/1/awk/
You could also just talk to the mail server using the script to send the emls with a templated body..
Edit: I have added the code to Github, for ease of use by other people. https://github.com/xrobau/smtphack
I realise I am somewhat necro-answering this question, but it wasn't answered and I needed to do this myself. Here's the code!
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
class SMTPHack
{
private $phpmailer;
private $smtp;
private $from;
private $to;
/**
* #param string $from
* #param string $to
* #param string $smtphost
* #return void
*/
public function __construct(string $from, string $to, string $smtphost = 'mailrx')
{
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->SMTPAutoTLS = false;
$mail->Host = $smtphost;
$this->phpmailer = $mail;
$this->from = $from;
$this->to = $to;
}
/**
* #param string $helo
* #return SMTP
*/
public function getSmtp(string $helo = ''): SMTP
{
if (!$this->smtp) {
if ($helo) {
$this->phpmailer->Helo = $helo;
}
$this->phpmailer->smtpConnect();
$this->smtp = $this->phpmailer->getSMTPInstance();
$this->smtp->mail($this->from);
$this->smtp->recipient($this->to);
}
return $this->smtp;
}
/**
* #param string $data
* #param string $helo
* #param boolean $quiet
* #return void
* #throws \PHPMailer\PHPMailer\Exception
*/
public function data(string $data, string $helo = '', bool $quiet = true)
{
$smtp = $this->getSmtp($helo);
$prev = $smtp->do_debug;
if ($quiet) {
$smtp->do_debug = 0;
}
$smtp->data($data);
$smtp->do_debug = $prev;
}
}
Using that, you can simply beat PHPMailer into submission with a few simple commands:
$from = 'xrobau#example.com';
$to = 'fred#example.com';
$hack = new SMTPHack($from, $to);
$smtp = $hack->getSmtp('helo.hostname');
$errors = $smtp->getError();
// Assuming this is running in a phpunit test...
$this->assertEmpty($errors['error']);
$testemail = file_get_contents(__DIR__ . '/TestEmail.eml');
$hack->data($testemail);

Categories