Programmatically downloading email body from gmail url - perl

I want to extract the body of an email from a gmail url: https://mail.google.com/mail/u/0/#inbox/FMfBlahwDrHlsBlahlzHWzQXHFKhjpTp1
I am using the Perl module: Net::IMAP::Simple::Gmail which gets me sequential access to the email inboxes and their imap ids. It also has a search method for searching emails. It also provides imap thread ids of each email.
But I haven't found an easy way to link the thread's URL in the browser to a particular imap email id so I can extract the body.

Here is a solution, though it's a bit convoluted:
Navigate to the gmail message thread of interest in your browser
Run the following JS in the developer console (or better, programmatically with Applescript, if using Safari, or some other browser automation program like WWW::Mechanize::Chrome) to get the "legacy" thread id:
document.querySelector('[data-legacy-thread-id]').getAttribute('data-legacy-thread-id')
Once you get the thread id, you then need to convert it to a decimal number. In Perl:
my $dec_num = sprintf("%d", hex($thread_id));
Now that you have obtained the thread id, you can use the Perl Mail::IMAPClient cpan module to obtain the messages in the thread by searching on the thread id:
use Mail::IMAPClient;
my $imap = Mail::IMAPClient->new(
Server => 'imap.gmail.com',
User => 'me',
Password => 'blah',
Ssl => 1,
Uid => 1,
);
my $folders = $imap->select('INBOX');
my $msgs = $imap->search("X-GM-THRID", $decimal_thread_id);
foreach my $msg (#$msgs) {
my $msg_st = $imap->message_string($msg);
# slice and dice messages with modules listed below
}
Now you can use cpan modules like Email::MIME and Email::MIME::Attachment::Stripper and Email::MIME::Encodings to parse the emails in $msgs and decode them as necessary.

Related

perl Email::Send with gmail fails with images

this question is related to HTML image not showing in Gmail , but the answers there do not (or no longer) work.
the problem is that my perl program (below) fails when my html-formatted messages that I want to send off as soon as an img tag is included. it does not matter whether the image itself is served from the google drive or not. I am guessing that I am running into a novel gmail restriction (my script used to work), but I am not sure.
(of course, this problem is not that my recipients do not see the image; it is that the sending perl script aborts with an error---unfortunately, not with more information explaining to me why it is an error. of course, I understand that my recipients need to agree to view images to prevent tracking.)
so here are my questions:
is this a gmail or a perl module problem?
is it possible to send images, so that if my recipients want to see
images from my website (preferably not just images from my google drive as in my example below), they can agree to see this?
is it possible to get a better error message from google about why it fails?
here is the [almost] working code:
#!/usr/bin/perl -w
use strict;
use warnings;
use Email::MIME::CreateHTML;
use Email::Send;
use Email::Send::Gmail;
my $toemail = 'ivo.welch#gmail.com';
my $subject = 'testing image mailing';
my $bodytext= '<html> <body> fails: <img src="https://drive.google.com/open?id=1K4psrWWolTSqx_f6MQP-T1-FMFpegT1Trg" alt="photo" /> </body> </html>\n';
use readcredentials;
my $gmailaccount= readcredentials( 'account' );
my $gmailuserlogin= readcredentials( 'userlogin');
my $gmailpasswd= readcredentials( 'gmailpassword');
eval {
my $message = Email::MIME->create_html(
header => [
From => $gmailaccount,
To => $toemail,
Subject => $subject,
],
body => $bodytext,
);
my $sender = Email::Send->new(
{ mailer => 'Gmail',
mailer_args => [
username => $gmailuserlogin,
password => $gmailpasswd,
]
}
);
$sender->send($message);
};
warn "Error sending email: $#" if $#;
print STDERR "emailed!\n";
I ran your script, with some modifications to remove the dependency on readcredentials to make it run in my environment, and the email was delivered with no problem. Problems could be:
You could have some problems with your gmail credentials.
The script downloads and attaches the image, so perhaps your local environment is preventing the image from being downloaded.
But without your specific error message, it's hard to diagnose any further.

Sending and Queuing emails in laravel

Hello i am trying to send emails in laravel this is currently what i do:
$parameters = array(
'date_of_purchase' => date('l, d m Y H:i A'),
'amount' => $amount,
);
// Sending Mail
Mail::queue('emails.bus-ticket-purchase', $parameters, function ($message) use ($customer_email) {
if ($message->to($customer_email, '')->subject('Ticket Purchase')) {
$all_good = true;
}
});
This works fine,all emails get delivered, but i started getting complaints about how some emails were taking about an hour to come through so i decided to read laravels documentation on emails and queues, what i found there was actually quite different from what i had done:
Laravel Mail Queues
So i run the artisan command to create the SendMail command and tried to folow the rest of the documentation but i still do not get it, it states that to send a mail(push it on a queue) i should do this:
Queue::push(new SendEmail($message));
Now where does the above code go? In my SendMail command or in my controller? Is there somewhere where i can see how this all works, i would really like someone to explain all this to me.

Using NET::SMTP in Perl to send .OFT templates

I currently have a working Perl code that fires off an email to the correct email address with my generic subject and content.
However, currently whenever a new user starts, we fire off a premade .oft template that says everything that they need to know. The .oft is stored on our server. I was wondering is there a way to alter the perl code to make it so it takes the to: but uses the .oft template to make the rest of the email??
so basically
$smtp = Net::SMTP->new('smtp.blah');
$smtp->('no-replay#blah.com');
$smtp->to('$personEmail');
$smtp->data();
$smtp->datasend($locationOfOftTemplate);
$smtp->dataend();
$smtp->quit;
AFAIK there is no module for handling this proprietary format. Instead, translate it to a standard templating system:
my $template = <<'TEMPLATE';
Good morning, [% name %]!
Today is your first day at work. You have already received your universal login
credentials:
[% ldap_user %]
[% ldap_pass %]
It works for authenticating at the Web proxy, mail system, Jabber and internal
services. Change the password ASAP: <[% ldap_web %]>
--
Yours sincerely, the greeting daemon
TEMPLATE
use Text::Xslate qw();
my $text = Text::Xslate->new(syntax => 'TTerse')->render_string($template, {
name => 'New Bee',
ldap_user => 'nbee',
ldap_pass => 'CON-GLOM-O',
ldap_web => 'http://192.168.0.1:8080/',
});
Use a MIME toolkit to create emails. HTML/multipart/attachments are easy with
Courriel::Builder:
use Courriel::Builder;
my $email = build_email(
subject('Welcome'),
from('no-reply#example.com'),
to('…'),
plain_body($text),
);
Finally, send it using the high-level library Email::Sender that gives you nice error checking and allows you to easily switch out transports - run local delivery for testing.
use Email::Sender::Simple qw(sendmail);
use Email::Sender::Transport::SMTP qw();
use Try::Tiny;
try {
sendmail(
$email,
{
transport => Email::Sender::Transport::SMTP->new({
host => 'smtp.example.invalid',
})
}
);
} catch {
warn "sending failed: $_";
};

how to send files as attachment in email in magento for downloadable products?

I am new to Magento. I am working on a web site which is selling downloadable products.
My client want purchased products should be sent via email in attachment?
Currently, I am developing in localhost so I am not sure whether magneto actually send product files in email or not?
Should I need to enable any option for that in configuration?
If you want to develop this at your localhost keep in mind, that you have to set up mail server or use some solutions from community like below link, to send it by gmail and other:
https://www.magentocommerce.com/magento-connect/smtp-pro-email-free-custom-smtp-email.html
You also can just configure your server to save mails without sending.
So you'll be able to review it.
Good article about how to send downloadable by email here:
https://magento.stackexchange.com/questions/49511/how-can-i-get-only-the-downloadable-product-url-in-email-template
But!!! keep in mind that the latest Magento use queue to send email (which runs by cron), so if you have such a distribution (for example 1.9+) you need to adjust code which you have from link above.
Here istwo solutions for this case:
Disable adding email to queue after order.
Just comment this part of code in "Mage_Core_Model_Email_Template"'s "send()" method:
// if ($this->hasQueue() && $this->getQueue() instanceof Mage_Core_Model_Email_Queue) {
/** #var $emailQueue Mage_Core_Model_Email_Queue */
/* $emailQueue = $this->getQueue();
$emailQueue->clearRecipients();
$emailQueue->setMessageBody($text);
$emailQueue->setMessageParameters(array(
'subject' => $subject,
'return_path_email' => $returnPathEmail,
'is_plain' => $this->isPlain(),
'from_email' => $this->getSenderEmail(),
'from_name' => $this->getSenderName(),
'reply_to' => $this->getMail()->getReplyTo(),
'return_to' => $this->getMail()->getReturnPath(),
))
->addRecipients($emails, $names, Mage_Core_Model_Email_Queue::EMAIL_TYPE_TO)
->addRecipients($this->_bccEmails, array(), Mage_Core_Model_Email_Queue::EMAIL_TYPE_BCC);
$emailQueue->addMessageToQueue();
return true;
}*/
So emails will be sent immediately (be aware, that if you have very big turnover with spikes it can create performance issue)
Second way is to save full path of attachment to table "core_email_queue" field - "message_parameters". You can do it adding url to array of argument here $emailQueue->setMessageParameters( in code above.
After that you can handle it in "Mage_Core_Model_Email_Queue"'s "send()" method
using standard "Zend Mail"'s method - "createAttachment()". Below link provides deeper explanation of this part.
https://magento.stackexchange.com/questions/9652/magento-send-file-attachements-in-emails
Hope it will help sombody.
Have a good day!!!

How do I use Perl's LWP to log in to a web application?

I would like to write a script to login to a web application and then move to other parts
of the application:
use HTTP::Request::Common qw(POST);
use LWP::UserAgent;
use Data::Dumper;
$ua = LWP::UserAgent->new(keep_alive=>1);
my $req = POST "http://example.com:5002/index.php",
[ user_name => 'username',
user_password => "password",
module => 'Users',
action => 'Authenticate',
return_module => 'Users',
return_action => 'Login',
];
my $res = $ua->request($req);
print Dumper(\$res);
if ( $res->is_success ) {
print $res->as_string;
}
When I try this code I am not able to login to the application. The HTTP status code returned is 302 that is found, but with no data.
If I post username/password with all required things then it should return the home page of the application and keep the connection live to move other parts of the application.
You may be able to use WWW::Mechanize for this purpose:
Mech supports performing a sequence of page fetches including following links and submitting forms. Each fetched page is parsed and its links and forms are extracted. A link or a form can be selected, form fields can be filled and the next page can be fetched. Mech also stores a history of the URLs you've visited, which can be queried and revisited.
I'm guessing that LWP isn't following the redirect:
push #{ $ua->requests_redirectable }, 'POST';
Any reason why you're not using WWW::Mechanize?
I've used LWP to log in to plenty of web sites and do stuff with the content, so there should be no problem doing what you want. Your code looks good so far but two things I'd suggest:
As mentioned, you may need to make the requests redirectable
You may also need to enable cookies:
$ua->cookie_jar( {} );
Hope this helps