Generate Mail and Open it in Outlook using Perl - perl

Does anyone know as how can I make a mail in perl using outlook and not send it just open it on the screen at the end of making the mail and let the user verify and send the mail. I am using Win32::OLE for making the mail.
PFB the code I am using:
sub Final_Mail_Outlook{
my($mailTo,$mailFrom,$subject,$body) = (#_);
my $Outlook = Win32::OLE->GetActiveObject('Outlook.Application') || Win32::OLE->new('Outlook.Application');
# Create Mail Item
my $item = $Outlook->CreateItem(0); # 0 = mail item.
unless ($item)
{
die "Outlook is not running, cannot send mail.\n";
}
$item->{'Subject'} = $subject;
$item->{'To'} = $mailTo;
$item->{'Body'} = $body;
$item->{'From'} = $mailFrom;
my $attach = $item->{'Attachments'};
my #outputFiles = glob("$OutputPath\\*.*");
foreach my $file (#outputFiles){
$attach->add($file);
}
$item->Send();
}
This sends the mail as I have called Send function, but I want to verify the mail generated. So is there a way to do so???

I just found an answer to it so thought of posting it also so that someone else needing an answer to this can get help. The key is to use the function Display() instead of Send(). PFB the modified code to open the mail and not send it.
sub Final_Mail_Outlook{
my($mailTo,$mailFrom,$subject,$body) = (#_);
my $Outlook = Win32::OLE->GetActiveObject('Outlook.Application') || Win32::OLE->new('Outlook.Application');
# Create Mail Item
my $item = $Outlook->CreateItem(0); # 0 = mail item.
unless ($item)
{
die "Outlook is not running, cannot send mail.\n";
}
$item->{'Subject'} = $subject;
$item->{'To'} = $mailTo;
$item->{'Body'} = $body;
$item->{'From'} = $mailFrom;
my $attach = $item->{'Attachments'};
my #outputFiles = glob("$OutputPath\\*.*");
foreach my $file (#outputFiles){
$attach->add($file);
}
$item->Display();
}

Related

How can I handle multiple outlook accounts using Perl

I have task to read mails from secondary mail account from outlook using perl.
Please check the following it may help you.But you should install respective modules.Reference from "http://www.perlmonks.org/?node_id=916759"
use Modern::Perl;
use Mail::POP3Client;
use MIME::QuotedPrint;
my $pop_user = 'XXXXXXXXXX';
my $pop_pass = 'XXXXXXXXXX';
my $pop_host = 'exchange3';
#connect to POP3 sever
my $pop = new Mail::POP3Client ( HOST => $pop_host );
$pop->User($pop_user);
$pop->Pass($pop_pass);
$pop->Connect()
or die "Unable to connect to POP3 server: ".$pop->Message()."\n";
#count number of items in POP3 mailbox
my $mailcount = $pop->Count();
for (my $i = 1; $i <= $mailcount ; $i++) {
my $header = $pop->Head($i); #gets the header
my $uni = $pop->Uidl($i); # gets the unquie id
my $body = $pop->Body($i);
$body = decode_qp($body); #decode quoted printable body
say "$uni";
say "$header\n";
say "$body";
}

Perl parse email and attachments from Outlook inbox

I'm using Mail::IMAPClient to connect to our Outlook mail server. I can get the mail just fine and print the text version of that mail to a file. But I'm having trouble using MIME::Parser to parse through the email.
I've tried giving the parser a file handle to the text file that I wrote the email to. I've tried giving the parser just the text of the email but it won't work how I'm expecting it to work. The entity parts always equals 0.
When I dump the entity skeleton I get
Content-type: text/plain
Effective-type: text/plain
Body-file: NONE
--
I can see all of the parts of the email in the file. The two PDFs that are attached are there, encoded in base64, so I know that the script is actually retrieving the email and the attachments. I've also tried parse and parse_data.
my $msgCount = 0;
$msgCount = $imap->message_count();
#or abortMission("", "Could not get message count: ". $imap->LastError );
if ( $msgCount > 0 ) {
#get all the messages from the inbox folder
my #msgseqnos = $imap->messages
or abortMission("", "Could not retreive messages:". $imap->LastError);
my ($x, $bh, $attachment, $attachmentName);
foreach my $seqno ( #msgseqnos ) {
my $input_file;
my $parser = new MIME::Parser;
my $emailText = $imap->body_string($seqno) # should be the entire email as text.
or abortMission("", "Could not get message string: " . $imap->LastError);
$parser->ignore_errors(1);
$parser->output_to_core(1);
open my $emailFileHandle, ">", "invoiceText.txt";
print $emailFileHandle $emailText;
#$imap->message_to_file($emailFileHandle, $seqno);
my $entity = $parser->parse_data($emailText);
$entity->dump_skeleton;
if ( $entity->parts > 0 ) {
for ( my $i = 0; $i < $entity->parts; $i++ ) {
my $subentity = $entity->parts($i);
# grab attachment name and contents
foreach $x ( #attypes ) {
if ( $subentity->mime_type =~ m/$x/i ) {
$bh = $subentity->bodyhandle;
$attachment = $bh->as_string;
$attachmentName = $subentity->head->mime_attr('content-disposition.filename');
open FH, ">$attachmentName";
print FH $attachment;
close FH;
#push #attachment, $attachment;
#push #attname, $subentity->head->mime_attr('content-disposition.filename');
}
}
}
}
else {
stillAGo("eData VehicleInvoices problem", "Perl can't find an attachment in an email in the VehicleInvoices folder of eData email address");
}
close $emailFileHandle;
# say $emailText;
# next;
#open OUT_FILE, ">invoiceText.txt";
#print OUT_FILE $emailText;
#print OUT_FILE $imap->bodypart_string($seqno,1);
#close OUT_FILE;
#print $emailText;
}
}
I'm trying to retrieve the attachments from emails automatically and save them to disk to be processed by another job.
I'd like to include the invoiceText.txt file so people can see the actual output but it's 1200 lines long. I'm not sure where to upload a file to link in here.
The body_string method doesn't return the entire email. As the documentation describes, and the name implies, it returns the body of the message, excluding the headers. That is why dump_skeleton shows no headers apart from the defaults
What you probably want, although I haven't tried it, is message_string, which does return the entire email
I see you've used message_to_file but commented it out. That would probably have worked if you got MIME::Parse to read from the file

PHPMailer attachment is not receiving

I have written code for sending mail with pdf file as attachment , mail sending is working. I used class.phpmailer.php. Below is my code.
$mpdf=new mPDF();
$mpdf->ignore_invalid_utf8 = true;
$stylesheet = file_get_contents('appstyle_pdf.css');
$mpdf->WriteHTML($stylesheet,1);
$mpdf->WriteHTML($output);
$comname = preg_replace("/[^A-Za-z0-9]/","",$_POST['company']);
$name = $dirname.str_replace(" ","-",$comname)."_".$time_stamp.".pdf";
$mpdf->Output($name,"F");
$filename = basename($name);
$file_size = filesize($name);
$content = chunk_split(base64_encode(file_get_contents($name)));
$mail = new PHPMailer;
$msg = 'Message';
$body = '<html><body><p>' . $msg . '</p></body></html>'; //msg contents
$body = preg_replace("[\\\]", '', $body);
$mail->AddReplyTo('no-replay#enkapps.com', "ACIC");
$mail->SetFrom('orders#enkapps.com', "ACIC Order");
$address = 'narendar_medoju#tecnics.com'; //email recipient
$mail->AddAddress($address, "NAME");
$mail->Subject = 'SUBJECT of ACIC order form';
$mail->MsgHTML($body);
$mail->AddStringAttachment($content , $filename);
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent Successfully please check attachement!";
}
When I use the above code attachment is coming to mail but file is corrupting. The error message is like "Adobe reader could not open abc.pdf because it is either not a supported file type or because the file has been damaged (for example, it was sent as an email attachment and wasn't correctly decoded)."
Why are you doing this?
$content = chunk_split(base64_encode(file_get_contents($name)));
...
$mail->AddStringAttachment($content , $filename);
That's completely unnecessary. Just do this:
$mail->addAttachment($name);
Also I suspect you are using an old version of PHPMailer; get the latest from github.

Downloading attachment from Exchange message with Perl

I am automatically downloading mails from an Exchange 2010 server via perl. So far I have managed to access the message via Exchange Web Services (EWS) and parse headers. Now I wonder how I can download the attachments of a message to a local temporary folder.
I am new to Perl language and cannot find the source code or documentation for the message data structure. Any help is appreciated.
use Email::Folder::Exchange;
use Email::Simple;
# some more code here....
my $folder = Email::Folder::Exchange->new($url, $user, $pass);
for my $message ($folder->messages) {
if ($message->header('Subject') =~ /Downloadable Message/) {
// How to access message's attachments?
}
}
So basically the trick is to convert the Email::Simple to Email::MIME and use Email::MIME::Attachment::Stripper to parse through each attachment. Easy ;-)
! I only copied the relevant parts... so you might need to extend it a little for reuse.
use Email::Folder::Exchange;
use Email::Simple;
use Email::MIME::Attachment::Stripper;
# some more code here....
my $folder = Email::Folder::Exchange->new($url, $user, $pass);
for my $message ($folder->messages) {
my $tmpMsg = Email::MIME->new($message->as_string);
my $stripper = Email::MIME::Attachment::Stripper->new($tmpMsg);
for my $a ($stripper->attachments()) {
next if $a->{'filename'} !~ /csv/i; #only csv attachments
my $tempdir = "C:\\temp\\";
my $tmpPath = $tmpdir . $a->{'filename'};
# Save file to temporary path
my $f = new IO::File $tmpPath, "w" or die "Cannot create file " . $tmpPath;
print $f $a->{'payload'};
}
}

PEAR Mail, Mail_Mime and headers() overwrite

I'm currently working on a reminder PHP Script which will be called via Cronjob once a day in order to inform customers about smth.
Therefore I'm using the PEAR Mail function, combined with Mail_Mime. Firstly the script searches for users in a mysql database. If $num_rows > 0, it's creating a new Mail object and a new Mail_mime object (the code encluded in this posts starts at this point). The problem now appears in the while-loop.
To be exact: The problem is
$mime->headers($headers, true);
As the doc. states, the second argument should overwrite the old headers. However all outgoing mails are sent with the header ($header['To']) from the first user.
I'm really going crazy about this thing... any suggestions?
(Note: However it's sending the correct headers when calling $mime = new Mail_mime() for each user - but it should work with calling it only once and then overwriting the old headers)
Code:
// sql query and if num_rows > 0 ....
require_once('/usr/local/lib/php/Mail.php');
require_once('/usr/local/lib/php/Mail/mime.php');
ob_start();
require_once($inclPath.'/email/head.php');
$head = ob_get_clean();
ob_start();
require_once($inclPath.'/email/foot.php');
$foot = ob_get_clean();
$XY['mail']['params']['driver'] = 'smtp';
$XY['mail']['params']['host'] = 'smtp.XY.at';
$XY['mail']['params']['port'] = 25;
$mail =& Mail::factory('smtp', $XY['mail']['params']);
$headers = array();
$headers['From'] = 'XY <service#XY.at>';
$headers['Subject'] = '=?UTF-8?B?'.base64_encode('Subject').'?=';
$headers['Reply-To'] = 'XY <service#XY.at>';
ob_start();
require_once($inclPath.'/email/templates/files.mail.require-review.php');
$template = ob_get_clean();
$crfl = "\n";
$mime = new Mail_mime($crfl);
while($row = $r->fetch_assoc()){
$html = $head . $template . $foot;
$mime->setHTMLBody($html);
#$to = '=?UTF-8?B?'.base64_encode($row['firstname'].' '.$row['lastname']).'?= <'.$row['email'].'>'; // for testing purpose i'm sending all mails to webmaster#XY.at
$to = '=?UTF-8?B?'.base64_encode($row['firstname'].' '.$row['lastname']).'?= <webmaster#XY.at>';
$headers['To'] = $to; // Sets to in headers to a new
$body = $mime->get(array('head_charset' => 'UTF-8', 'text_charset' => 'UTF-8', 'html_charset' => 'UTF-8'));
$hdrs = $mime->headers($headers, true); // although the second parameters says true, the second, thrid, ... mail still includes the To-header form the first user
$sent = $mail->send($to, $hdrs, $body);
if (PEAR::isError($sent)) {
errlog('error while sending to user_id: '.$row['id']); // personal error function
} else {
// Write log file
}
}
There is no reason to keep the old object and not creating a new one.
Use OOP properly and create new objects - you do not know how they work internally.