In several Delphi XE2 projects, I have set up Eurekalog to send bug reports via "HTTP upload" which works well, as I use a PHP script to catch the bug report, save it in a directory and send it to me via email:
<?php
require 'PHPMailerAutoload.php';
foreach ($_FILES as $key => $value)
{
$uploaded_file = $_FILES[$key]['tmp_name'];
$server_dir = 'upload/';
$server_file = $server_dir . date("Y-m-d H-i-s ") . basename($_FILES[$key]['name']);
$ext = strtoupper(pathinfo($server_file, PATHINFO_EXTENSION));
if ($ext != 'EL')
{
continue;
}
if (move_uploaded_file($uploaded_file, $server_file))
{
echo '<html>';
echo '<head>';
echo '<META HTTP-EQUIV="CONTENT-TYPE" CONTENT="TEXT/HTML; CHARSET=UTF-8">';
echo '<title>Bug submission</title>';
echo '</head>';
echo '<body>';
echo 'Thank you!<br />';
echo "<!--\n";
echo "<EurekaLogReply>Thank you for your feedback!</EurekaLogReply>\n";
echo "-->";
echo '</body>';
echo '</html>';
SendBugReportMessage('auserofmyprogram#usersofmyprogram.com',
'A User of my program',
'Eurekalog Bug Report',
'This is a bug report from Eurekalog.',
'eurekalog.bugreport#mysite.com',
$server_file,
basename($server_file)
);
}
}
function SendBugReportMessage($AFrom, $AFromName, $ASubject, $ABodyText, $ARecipient, $AFileToAttach, $ANameOfFile)
{
$email = new PHPMailer();
$email->From = $AFrom;
$email->FromName = $AFromName;
$email->Subject = $ASubject;
$email->Body = $ABodyText;
$email->AddAddress($ARecipient);
$file_to_attach = $AFileToAttach;
$email->AddAttachment($file_to_attach, $ANameOfFile);
return $email->Send();
}
?>
Now I have several programs using this very same PHP script to upload their bug reports. However, the bug report sent to this PHP script has always the name "BugReport". So, in the PHP script how can I get the name of the program which sent the bug report, so I can save it by attaching the program name and include the program name in the mail subject? Or could there be a solution by implementing something on the side of the Delphi code? Or in Eurekalog?
Eurekalog version is 7.1.0.0
You can use web-fields for that. EurekaLog has OnCustomWebFieldsRequest event handler, which allow you to alter web-fields for any web-based send method (such as HTTP upload, bug trackers with HTTP API, etc.).
Assign such event hanlder:
uses
EEvents;
procedure AddApplicationName(const ACustom: Pointer; ASender: TObject { TELWebSender }; AWebFields: TStrings; var ACallNextHandler: Boolean);
begin
AWebFields.Values['Application'] := AnsiLowerCase(ExtractFileName(ParamStr(0)));
end;
initialization
RegisterEventCustomWebFieldsRequest(nil, AddApplicationName);
end.
Then, you can access your new "Application" field from your script. For PHP it will be $_REQUEST["Application"] or $_POST["Application"]
For this particular task you can also use OnCustomFileName event handler to alter file name used for sending. You are interested in AFileType = ftZIP (if you are going to send packed .elp report) or AFileType = ftBugReport (if you are going to send unpacked .el report).
Related
UPDATE #2 - FINAL ANSWER
I figured and you'll see in the comments below that my comparison symbol needed to be changed. So I took the code in Update #1 and simply changed this:
return filemtime($a) < filemtime($b);
to:
return filemtime($a) > filemtime($b);
And that did it!!! Thanks everyone for the dialog.
UPDATE
I've updated my code. Now I'm getting the attachment sent but again, it's not grabbing the latest one. Here's my latest code:
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'php/PHPMailer2020/src/Exception.php';
require 'php/PHPMailer2020/src/PHPMailer.php';
$dir = "php/sketch-drawings/";
$pics = scandir($dir);
$files = glob($dir . "*.*");
usort($files, function($a, $b){
return filemtime($a) < filemtime($b);
});
foreach ($files as $pics) {
echo '<img src="'. $pics . '">';
}
// SEND EMAIL W/ ATTACHMENT OF LATEST IMAGE
$mail = new PHPMailer();
$mail->Sender = "hello#myemail.com";
$mail->From = "mail#myemail.com";
$mail->FromName = "My Company";
$mail->AddReplyTo( "mail#mycompany.com", "DO NOT REPLY" );
//$mail->AddAddress("info#mycompany.com");
$mail->AddAddress("myemail#gmail.com");
$mail->isHTML(true);
$mail->Subject = "Latest Sketch Image";
$mail->Body = "Latest Image Attached! \n\n Thanks - XYZ Digital.";
$mail->AddAttachment($pics);
if(!$mail->Send()) {
echo 'Email Failed To Send.';
}
else {
echo 'Email Was Successfully Sent.';
echo "</p>";
echo '<script language="javascript">';
echo 'alert("Thanks! Message Sent")';
echo '</script>';
}
$mail->ClearAddresses();
?>
This issue:
The AddAttachment($filepath) returns an attachment, but it's not the most recent one-- I need it to always return the most recent image in the directory.
Here's what I'm doing:
I've created a web application that is basically a sketch pad. When a user taps on "Save" the code snaps a pic of the element saves it to a directory and then sends an email to the pre-defined address with the snap of the canvas as an attachment... and the issue is above.
What I've done:
I've looked all over the place for a solve -- seems as though the only find is around uploading the attachments via a web form--which isn't my issue. My workflow is different and why I'm here asking now. :)
What's not working:
Everything works except for the attachment part. I'm using PHPMailer but for some reason, the attachment is never the latest one. In fact, it seems to always be the same attachment no matter what.
I tried to get the first element in the array doing this (which I echo in the bottom of the code and it returns the right image:
$mail->addAttachment($sketches[0]);
this doesn't work -- it sends the email, but nothing attached.
How in the world, can I adjust my code below to get the latest attachment? I appreciate any help as PHP is not my area of expertise.
See the code below...
<?php // NEW
// DEFINE ERRORS
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer2020/src/Exception.php';
require 'PHPMailer2020/src/PHPMailer.php';
// GET LATEST UPLOAD -- AND HAVE IT STORED IN DOM (WHEN NEEDED)
$path = ('sketch-drawings');
// Sort in descending order
$sketches = scandir($path, 1);
$latest_ctime = 1;
$latest_filename = '';
$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
// could do also other checks than just checking whether the entry is a file
if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
}
// SEND EMAIL W/ ATTACHMENT OF LATEST IMAGE
$mail = new PHPMailer();
$mail->Sender = "hello#myemail.com";
$mail->From = "mail#myemail.com";
$mail->FromName = "My Company";
$mail->AddReplyTo( "mail#myemail.com", "DO NOT REPLY" );
//$mail->AddAddress("info#myemail.com");
$mail->AddAddress("myemail#gmail.com");
$mail->isHTML(true);
$mail->Subject = "Latest Sketch Image";
$mail->Body = "Latest Image Attached! \n\n Thanks - XYZ Digital.";
$mail->AddAttachment($filepath);
//$mail->addAttachment($sketches);
if(!$mail->Send()) {
echo 'Email Failed To Send.';
} else {
echo $filepath;
echo "<br><br>";
print $latest_filename;
echo "</p>";
echo "<p>";
print $sketches[0];
echo "</p>";
echo "<p>";
echo 'Email Was Successfully Sent.';
echo "</p>";
echo '<script language="javascript">';
echo 'alert("Thanks! Message Sent")';
echo '</script>';
}
$mail1->ClearAddresses();
}
?>
PHP's dir() function returns items in an indeterminate order. If you want to retrieve files ordered by date, see this answer.
Scenario:
I am using Gmail API via PHP.
Purpose:
I want to edit the HTML part of the message.
Precisely, I want to add a tracking image in the message, keeping the attached files.
What am I doing?:
This:
//UPDATE
$opt_param = array();
$d = new Google_Service_Gmail_Draft();
$d->setMessage($msg);
try {
$plom = $service->users_drafts->update('me', $draftito, $d, $opt_param);
echo 'Draft with ID: ' . $draftito . ' updated successfully.<hr><hr>';
var_dump($plom);
} catch (Exception $e) {
echo 'An error occurred: ' . $e->getMessage();
}
//SEND
$de = new Google_Service_Gmail_Draft();
$de->setId($draftito);
$plom=$service->users_drafts->send('me', $de);
var_dump($plom);
Probably the key point here is $msg.
I set it up with setRaw() message:
$mime = ...
$msg = new Google_Service_Gmail_Message();
$msg->setRaw($mime);
But I do not know how to handle the attached files here.
I know I am getting things mixed up, but the online docs for PHP are really obscure.
Is there any way to just edit the HTML version of the message without touching all the multipart Message?
i need to create a custom mailing script in magento in Shell folder. I got the sample script from internet. this script was described as a stand alone script and no template id's are required and this type of script is what I needed and program didn't work for me.Below is the script.
require '../app/Mage.php';
ini_set('display_errors', true);
ini_set('max_execution_time', 3600); // just put a lot of time
ini_set('default_socket_timeout', 3600); // same
set_time_limit(0);
class Mage_Shell_Report
{
public function myfunc()
{
$body = "Hi there, here is some plaintext body content";
$mail = Mage::getModel('core/email');
$mail->setToName('reig');
$mail->setToEmail('rieg.philippe#neuf.fr');
$mail->setBody($body);
$mail->setSubject('The Subject');
$mail->setFromEmail('boutique#infosys.com');
$mail->setFromName("divine");
$mail->setType('text');// You can use 'html' or 'text'
try {
$mail->send();
if($mail->send())
{
$msg = true;
echo "<br>mail sent<br>";
}
else
{
echo "<br>mail not send<br>";
}
Mage::getSingleton('core/session')->addSuccess('Your request has been sent');
}
catch (Exception $e) {
Mage::getSingleton('core/session')->addError('Unable to send.');
$this->_redirect('');
}
echo "<br>end program<br>";
}
}
echo "out-1";
$shell1 = new Mage_Shell_Report();
$shell1->myfunc();
?>
This program shows no error . Though mail function returns success , i am not receiving any mail. i am testing in local using SMTP. Other email's, like order email, customer emails are sent successfully and can be viewed in SMTP mailbox. I browsed through pages and came to know that this issue has something to do with queuing but am not clear about that. Kindly help me out
I am using EFUMultiple Uploader to receive files on my site. Does anyone know of a tutorial that will teach me how I can be notified each time there is a new file or batch of files in my uploads folder?
It will become annoying, fast, I can promise you that.
But either way, in your upload script, you'll want to use either the mail() function or, for example the PHPMailer library if you don't have a SMTP server configured on your PHP installation.
Consider this (untested) script:
#!/usr/bin/env php
<?php
// Warning: this script and UPLOADED_FILES_DB, for security reasons, should not be in UPLOAD_PATH.
define('UPLOAD_PATH', '...');
define('UPLOADED_FILES_DB', 'uploaded_files');
define('MAIL_TO', 'you#example.com');
define('MAIL_FROM', 'cron#example.com');
define('MAIL_SUBJECT', 'Uploaded files');
// Get old files:
if (file_exists(UPLOADED_FILES_DB)) {
$old_files = unserialize(file_get_contents(UPLOADED_FILES_DB));
} else {
$old_files = array();
}
// Get current files:
$current_files = array();
foreach (new DirectoryIterator(UPLOAD_PATH) as $file_info) {
if (!$file_info->isDot()) {
$current_files[$file_info->getFilename()] = filemtime($file_info->getFilename());
}
}
// Update database:
file_put_contents(serialize($current_files), UPLOADED_FILES_DB);
// Compute differences:
$added_files = array_diff(array_keys($old_files), array_keys($current_files));
$removed_files = array_diff(array_keys($current_files), array_keys($old_files));
$changed_files = array_diff_assoc($old_files, $current_files);
// Send message:
$headers = 'From: ' . MAIL_FROM . "\r\n";
$message = 'Added files: ' . implode(', ', $added_files);
mail($to, $subject, $message, $headers);
Then you would put that script on a cron job to execute every day or so, or you can include it in wherever your upload code is — though, the latter approach would get annoying quickly.
I'm trying to write a script which downloads all mail in a certain folder without a custom flag, let's call the flag $aNiceFlag for now; after I've fetched a mail I want to flag it with $aNiceFlag. However before tackling the flag problem I've got a problem to extract the content i need from the mail right now.
This is the information I need:
Sender (email and name if possible)
Subject
Receiver
Plain text body (if only html is available I will try convert it from html to plaintext)
Time sent
I can easily get the subject by using $mailObject->subject. I'm looking at the Zend Documentation but it's a bit confusing for me.
Here's my code right now, I'm not supposed to echo out the content but that's just for now while testing:
$this->gOauth = new GoogleOauth();
$this->gOauth->connect_imap();
$storage = new Zend_Mail_Storage_Imap(&$this->gOauth->gImap);
$storage->selectFolder($this->label);
foreach($storage as $mail){
echo $mail->subject();
echo strip_tags($mail->getContent());
}
I'm accessing the mail using google oAuth. $this->label is the folder I want to get. It's quite simple for now but before making it to complex I want to figure out the fundamentals such as a suitable way to extract all above listed data into separate keys in an array.
You can get the headers for sender, receiver and date quite easily using the same technique you used for the subject, however the actual plaintext body is a bit more tricky, here's a sample code which will do what you want
$this->gOauth = new GoogleOauth();
$this->gOauth->connect_imap();
$storage = new Zend_Mail_Storage_Imap(&$this->gOauth->gImap);
$storage->selectFolder($this->label);
// output first text/plain part
$foundPart = null;
foreach($storage as $mail){
echo '----------------------<br />'."\n";
echo "From: ".utf8_encode($mail->from)."<br />\n";
echo "To: ".utf8_encode(htmlentities($mail->to))."<br />\n";
echo "Time: ".utf8_encode(htmlentities(date("Y-m-d H:s" ,strtotime($mail->date))))."<br />\n";
echo "Subject: ".utf8_encode($mail->subject)."<br />\n";
foreach (new RecursiveIteratorIterator($mail) as $part) {
try {
if (strtok($part->contentType, ';') == 'text/plain') {
$foundPart = $part;
break;
}
} catch (Zend_Mail_Exception $e) {
// ignore
}
}
if (!$foundPart) {
echo "no plain text part found <br /><br /><br /><br />\n\n\n";
} else {
echo "plain text part: <br />" .
str_replace("\n", "\n<br />", trim(utf8_encode(quoted_printable_decode(strip_tags($foundPart)))))
." <br /><br /><br /><br />\n\n\n";
}
}