base64-Encoding breaks smime-encrypted emaildata - perl

I'm using Mime::Lite to create and send E-Mails. Now I need to add support for S/Mime-encryption and finally could encrypt my E-Mail (the only Perllib I could install seems broken, so I'm using a systemcall and openssl smime), but when I try to create a mime-object with it, the E-Mail will be broken as soon as I set the Content-Transfer-Encoding to base64. To make it even more curious, it happens only if I set it via $myMessage->attr. If I'm using the constructor ->new everything is fine, besides a little warning which I suppress by using MIME::Lite->quiet(1);
Is it a bug or my fault? Here are the two ways how I create the mime-object.
Setting the Content-Transfer-Encoding via construtor and suppress the warning:
MIME::Lite->quiet(1);
my $msgEncr = MIME::Lite->new(From =>'me#myhost.com',
To => 'you#yourhost.com',
Subject => 'SMIME Test',
Data => $myEncryptedMessage,
'Content-Transfer-Encoding' => 'base64');
$msgEncr->attr('Content-Disposition' => 'attachment');
$msgEncr->attr('Content-Disposition.filename' => 'smime.p7m');
$msgEncr->attr('Content-Type' => 'application/x-pkcs7-mime');
$msgEncr->attr('Content-Type.smime-type' => 'enveloped-data');
$msgEncr->attr('Content-Type.name' => 'smime.p7m');
$msgEncr->send;
MIME::Lite->quiet(0);
Setting the Content-Transfer-Encoding via $myMessage->attr which breaks the encrypted Data, but won't cause a warning:
my $msgEncr = MIME::Lite->new(From => 'me#myhost.com',
To => 'you#yourhost.com',
Subject => 'SMIME Test',
Data => $myEncryptedMessage);
$msgEncr->attr('Content-Disposition' => 'attachment');
$msgEncr->attr('Content-Disposition.filename' => 'smime.p7m');
$msgEncr->attr('Content-Type' => 'application/x-pkcs7-mime');
$msgEncr->attr('Content-Type.smime-type' => 'enveloped-data');
$msgEncr->attr('Content-Type.name' => 'smime.p7m');
$msgEncr->attr('Content-Transfer-Encoding' => 'base64');
$msgEncr->send;
I just don't get why my message is broken when I'm using the attribute-setter. Thanks in advance for your help!
Besides that i'm unable to attach any file to this E-Mail without breaking the encrypted message again.

To debug this
Make a script call showmail.pl
#!/usr/bin/perl
while (<STDIN>) { print $_; }
Test it like
use MIME::Lite;
use Net::SMTP;
use MIME::Base64;
$myEncryptedMessage = encode_base64("This is not valid encrypted message\n");
MIME::Lite->send('sendmail', "./showmail.pl"); ## Add this for debugging.
MIME::Lite->quiet(1); my $msgEncr = MIME::Lite->new(From =>'me#localhost',
To => 'you#localhost',
Subject => 'SMIME Test',
Data => $myEncryptedMessage,
'Content-Transfer-Encoding' => 'base64');
$msgEncr->attr('Content-Disposition' => 'attachment');
$msgEncr->attr('Content-Disposition.filename' => 'smime.p7m');
$msgEncr->attr('Content-Type' => 'application/x-pkcs7-mime');
$msgEncr->attr('Content-Type.smime-type' => 'enveloped-data');
$msgEncr->attr('Content-Type.name' => 'smime.p7m');
$msgEncr->send();
you should see something like.
MIME-Version: 1.0
Content-Disposition: attachment; filename="smime.p7m"
Content-Length: 49
Content-Type: application/x-pkcs7-mime; name="smime.p7m"; smime-type="enveloped-data"
X-Mailer: MIME::Lite 3.028 (F2.74; B3.07; Q3.07)
Date: Mon, 23 Mar 2012 10:40:51 -0400
From: me#localhost
To: you#localhost
Subject: SMIME Test
Content-Transfer-Encoding: base64
VGhpcyBpcyBub3QgdmFsaWQgZW5jcnlwdGVkIG1lc3NhZ2UK
The message is encoded base64, but the real message still needs to be correctly
encypted. You need to make sure that is the case since $myEncryptedMessage is
passed in. With the debug output, you can compare with a known good encrypted mail
and see if the headers are good, as far as I can see the headers are fine, it is probably
the data that is not valid.

I am not able to test this with a real mail client, but this is what I think may work for multi-parts.
use MIME::Lite;
use Net::SMTP;
use MIME::Base64;
MIME::Lite->send('sendmail', "./showmail.pl"); ## <---- for testing only
my $from_address = "nobody#localhost";
my $to_address = "somebody#localhost";
my $mail_host = "localhost";
my $subject = "Subject list";
my $message_body = "Attachment list";
my #files = ("crypt.data1","crypt.data2");
$msg = MIME::Lite->new (
From => $from_address,
To => $to_address,
Subject => $subject,
Type =>'multipart/mixed'
) or die "Error creating multipart container: $!\n";
foreach $c(#files) {
$msg->attach (
Disposition => 'attachment',
Type => "application/x-pkcs7-mime; name=smime.p7m; smime-type=enveloped-data",
Path => $c,
) or die "Error adding $c: $!\n";
}
$msg->send;

As I said in one comment the difference in setting the encoding in the construtor of the mimeobject or with the ->attr-Setter is, that the construtor just sets the encoding in the mimeheader. By using the ->attr-Setter mime encodes the data with base64.
So in my case, my previously generated mimeobject - which is base64-encoded and with s/mime encrypted - read from a file needs to set the encoding in the construtor (and suppress the warning) so no more encoding will be done by mime. Otherwise mime will encode the data again and therefore break the encryption and the email itself.
I finally got attachments to work. To achieve this I create a normal multipart/mixed mimeobject, print this object into a normal file, encrypt this file with openssl smime, read this whole file (except the 6 headerlines) into a variable and use this as the datainput. Additionally I set the Content-Transfer-Encoding to base64 using the construtor (so no encoding is done to my data).
I hope this will help someone else then me ;)

Replace $myEncryptedMessage with encode_base64($myEncryptedMessage)
and use MIME::Base64;

Related

How to send pdf from URL using perl and sendmail [Mail::Sendmail]

I have a legacy app that needs to change. it is written in perl and uses send::mail to send mails to users. Previously we sent links in the email message body but now they want pdf attachments instead. The PDF's are generated on another server using php.
the workflow would be
create the email body
get the pdf from another server via a URL
add the pdf as an attachment to the email
send it.
I think I can use
use LWP::Simple;
unless (defined ($content = get $URL)) {
die "could not get $URL\n";
}
to get the contents of the URL but I can't figure out how to use that var as an attachment in sendmail. current sendmail code is:
my %maildata = (To => $to,
From => 'OurSite - Billing <billing#ourSite.com>',
Organization => 'OurSite, LLC http://www.OurSite.com/',
Bcc => 'sent-billing#ourSite.com',
Subject => $subject{$message} || 'ourSite invoice',
Message => $body
);
print STDERR "notify1 now calling sendmail\n";
sendmail(%maildata) || print STDERR $Mail::Sendmail::error;
The other issue I have is I don't know how to find out if the version of sendmail I have (old freebsd system) is even capable of sending attachments ?
ok thanks for the posters who gave me some direction / the will to give it a go.
In the end I built the mime body doing the following
use LWP::Simple;
use MIME::Base64;
unless (defined ($content = get $URL)) {
die "could not get $URL\n";
}
my $pdfencoded = encode_base64($content);
my %maildata = (To => $to,
From => 'OurSite - Billing <billing#ourSite.com>',
Organization => 'OurSite, LLC http://www.OurSite.com/',
Bcc => 'sent-billing#ourSite.com',
Subject => $subject{$message} || 'ourSite invoice',
);
my $boundary = "====" . time() . "====";
$maildata{'content-type'} = "multipart/mixed; boundary=\"$boundary\"";
$maildata{'Message'} = "--".$boundary."\n"."Content-Type: text/plain\n".$body.
"\n--".$boundary."\nContent-Transfer-Encoding: base64\nContent-Type:
application/pdf; name=\"invoice.pdf\"\n".$pdfencoded."\n--".$boundary."--";
sendmail(%maildata) || print STDERR $Mail::Sendmail::error;
This gave me a hand built MIME format for the body content.
Thanks for the help !

Sending using Email::Simple with To/From in body text instead of headers

Currently we are using a print to send an html mail via a sendmail pipe, which works fine.
$fh->open( q{|sendmail -f<fromaddress> .......} );
This comes from a template which contains text like...
From: <Fromaddress>
Reply-to: <replyaddress>
Subject: etc
Mine-Version: 1.o
Content-Type: text/html
<!DOCTYPE html...
<html...
rest of body
I am now trying to use Email::Simple with the same text
my $email = Email::simple->create(
header => $header,
body => $body
);
sendmail( $email, { transport => $transport });
My headers are like
[ To => <toaddress>, From => <fromaddress>, 'Content-Type' => 'text/html' ]
This all sends fine, except it includes also the 'From:.. To:: Subject..' as part of the html to be displayed also, whereas sendmail consumes this to be used.
I could use regex to strip out the header content that's included in the text (as it's already generated, but that feels risk prone and clunky), but I'm wondering, is there an Email::Simple way of discarding that, or using only the html instead of the From/To/Subject specific headers provided to Email::Simple ?
I have looked here but can't see any reference to that.
I assume your $body variable contains the text from one of your template files. And as those templates contain the headers, they will end up duplicated in the body of your email messages.
The best approach is to edit your templates to remove the header sections.
But if you can't do that for some reason, you can pre-process $body before passing it to the create() method. Something like this, perhaps:
(undef, $body) = split /\n\n/, $body, 2;
Actually the answer is simpler than I thought...
If you just use
my $email = Email::Simple->new( $text );
sendmail( $email, { transport => $transport });
It will use the headers from the text/body, and not include them in the main body.
If you use
my $email = Email::Simple->create( $text );
sendmail( $email, { transport => $transport });
It seems to need the separate headers, and sends out the headers in the text as part of the main data/html that's sent out.

Create Email object and update body_str afterwards in Perl

I am trying to update a script so that it can send an email using the Email::MIME object.
I create email object, and then later on update the body of the message, as the message body can change depending on different circumstances.
I have the following code
my $message = Email::MIME->create(
header_str => [
From => 'someone#example.com',
To => 'someoneelse#example.com',
Subject => 'This is the subject'
],
attributes => {
encoding => 'quoted-printable',
charset => 'ISO-8859-1'
}
);
if ( $i > 1 ) {
$message->body_str = "Here's one message";
}
else {
$message->body_str = "Here's seconds message";
}
When I do the above I get the following error:
Can't modify non-lvalue subroutine call
The error line is referencing where I am updating body_str
$message->body_str is a get method, not set.
What you are looking for is body_set or probably body_str_set.
#!/usr/bin/perl
use strict;
use warnings;
use Email::MIME;
my $message = Email::MIME->create(
header_str => [
From => 'someone#example.com',
To => 'someoneelse#example.com',
Subject => 'This is the subject'
],
attributes => {
encoding => 'quoted-printable',
charset => 'ISO-8859-1'
}
);
#put your conditionals here
print $message->body_set('Blah');
According to the documentation, you must use body_set or body_str_set to change the value of the body text
Use
$message->body_set("Here's one message")
if you want to pass a simple 7-bit ASCII string, or if your string is already encoded to conform with the message's character set. The module will automatically encode it according to the message's character set before storing it
Or use
$message->body_str_set("Here's one message")
if you want to pass a general unencoded Unicode string. You will need to be careful about any literal strings you use, as the result depends on the encoding your editor adopts when it writes the file
It is generally best to add use utf8 at the top of your program, and ensure that your editor writes UTF-8 data. That will cause Perl to read your source code and decode it as UTF-8, storing your strings as basic Unicode data that you can pass to body_str_set.

sending multipart mail in perl

i am trying to send a mail through Perl script using net::smtp module.It works fine when i send the normal mail without any attachment.i wont receive any mail.
use Net::SMTP;
use MIME::Base64;
use File::Basename;
use MIME::Base64 qw( encode_base64 );
use MIME::Base64 qw( decode_base64 );
#attachments = 'C:\Users\ups7kor\Desktop\scripts\commadnline\appending.pl';
$toAddress = '***';
$fromAddress = '***';
$ServerName = '***';
my $boundary = 'End Of mail';
my $smtp = Net::SMTP->new($ServerName, Timeout => 60) or print $failureLogHandler ++$errrorCount.")ERROR:Could not create SMTP object . \n\t please check SMPT Adress in $iniFileData{INI_SMTP_SERVER_NAME} of $iniFileSection{INI_EMAIL} section ";
$smtp->mail($fromAddress);
$smtp->recipient($toAddress, { SkipBad => 1 });
$smtp->data();
$smtp->datasend("To: $toAddress\n");
$smtp->datasend("From: $fromAddress\n");
$smtp->datasend("Subject: $subject\n");
$smtp->datasend("MIME-Version: 1.0\n");
$smtp->datasend("Content-type: multipart/mixed;\n\tboundary=\"$boundary\"\n");
$smtp->datasend("--$boundary\n");
$smtp->datasend("Content-type: text/plain\n");
$smtp->datasend("Content-Disposition: quoted-printable\n");
$smtp->datasend("\n $messageBody\n");
if(#attachments)
{
$smtp->datasend("--$boundary\n");
foreach $attachment (#attachments)
{
open(DAT, $attachment) || die("Could not open text file!");
my #textFile = <DAT>;
close(DAT);
my $filename = basename($attachment);
$smtp->datasend("Content-Type: application/text; name=\"$filename\"\n");
$smtp->datasend("Content-Disposition: attachment; filename=\"$filename\"\n");
$smtp->datasend("\n");
$smtp->datasend("#textFile\n");
}
}
$smtp->datasend("--$boundary --\n");
$smtp->dataend();
$smtp->quit;
But if i try the same code in other machine it works file.
Why the same code is not working in my machine and working fine in other machine.
Please help out.
You're using some rather low-level tools for building your message. That would probably work, but you'd need to implement all of the rules for building MIME messages - which sounds far too much like hard work.
Whenever I want to do something with email and Perl, I look for the appropriate module in the Email::* namespace. I'd probably start with Email::MIME, but I note that now includes a pointer to Email::Stuffer, which might well be even simpler.
You could use MIME::Lite module.
See: https://metacpan.org/pod/MIME::Lite#Create-a-multipart-message
Synopsis:
### Create the multipart "container":
$msg = MIME::Lite->new(
From =>'me#myhost.com',
To =>'you#yourhost.com',
Cc =>'some#other.com, some#more.com',
Subject =>'A message with 2 parts...',
Type =>'multipart/mixed'
);
### Add the text message part:
### (Note that "attach" has same arguments as "new"):
$msg->attach(
Type =>'TEXT',
Data =>"Here's the GIF file you wanted"
);
### Add the image part:
$msg->attach(
Type =>'image/gif',
Path =>'aaa000123.gif',
Filename =>'logo.gif',
Disposition => 'attachment'
);
Update: As per Dave's comment:
Check out Email::Stuffer module. Creating multipart message with it is really simple.
Email::Stuffer->to('Simon Cozens<simon#somewhere.jp>')
->from('Santa#northpole.org')
->text_body("You've been good this year. No coal for you.")
->attach_file('choochoo.gif')
->send;
You can use Mail::Sender module to send mails with attachment with body included. Just a small example of how to implement if you have this module in place.
my $sender = new Mail::Sender {smtp => 'server name', from =>
'emailId'};
$sender->MailFile( {to => 'xxx.gmail.com,yyy.gmail.com', subject => 'some subject that you want to put',
msg => "Body of the mail", file => 'path for the attachment that you need to send'} );

MIME::Lite error attaching file perl

500 Internal server error when attaching a file, but not when sending without attachment.
use MIME::Lite;
$msg = MIME::Lite->new(
From =>'email#domain.com',
To =>'email#domain2.com',
Subject =>'A message with 2 parts...',
CC => '',
Type =>'TEXT',
Data =>'Thank you for your interest in'
);
### If I comment out the following attachment code the email sends OK, otherwise i get 500 internal server error
$msg->attach(
Type =>'image/gif',
Path =>'/images/tree.gif',
Filename =>'tree.gif',
Disposition => 'attachment'
)or die "error attaching file\n";
$msg->send;
Just a suggestion and a few things I can recommend for this also. Applying this method will allow you to split your text/html parts and attachments to include, so you can send a message with multi attributes if you would like.
use strict;
use warnings;
use MIME::Lite;
my $msg = MIME::Lite->new(
To => 'email#domain2.com',
From => 'email#domain.com',
Subject => 'A message with 2 parts...',
Type => 'multipart/alternative',
);
# Make my text part
my $txt = MIME::Lite->new(
Type => "text/plain",
Data => 'Thank you for your interest in',
);
# Make my html part
my $html = MIME::Lite->new(
Type => 'multipart/related',
);
# Here you can attach what html tags you would like to include.
$html->attach(
Type => 'text/html',
Data => "<b>my html is here</b>",
);
$html->attach(
Type => 'image/gif',
Id => 'tree.gif',
Path => "../images/tree.gif",
);
$msg->attach($txt);
$msg->attach($html);
my $data = $msg->as_string;
Also I seen where you were using die for error handling, no need to do that here.
The error ended up being in that the URI has to be written relative to the script.
So I had to change /images/tree.gif
To
../images/tree.gif