Solved

Attaching a file to mail

Posted on 1998-09-05
36
321 Views
Last Modified: 2010-08-05
First Thanks!!!!!!!!
Second, if I'm using a Unix machine how can I attach a file to a mail? I have a script which will handle automatic mailing but I need to be able to attach a file.  Need more specifics, I'll get them.  Don't have right now.
0
Comment
Question by:guadalupe
  • 20
  • 14
  • +1
36 Comments
 
LVL 5

Expert Comment

by:b2pi
ID: 1204733
Are you sending mail via perl or shelling out to a mail program?
0
 
LVL 3

Author Comment

by:guadalupe
ID: 1204734
I'm using UNIX'S SENDMAIL.

Thanks
0
 
LVL 84

Expert Comment

by:ozo
ID: 1204735
use MIME::Lite;
0
 

Accepted Solution

by:
vipin072998 earned 100 total points
ID: 1204736
To attach a a file to a mail firstly you have to get the content type ,use mime.Declare Buffer for Data reading from disk and declare a scalar variable to hold the maximum amount of data that can be attached with mail . You have to get the server name on which file has to be uploaded.Initially read the file at the client and divide the file into parts by placing divider conent and write this file to server file after removing divider content.
This is a sort of file upload .example is given below:
#!d:\perl\bin\perl.exe

require 5.001;
#use strict;
require "./cgi-lib.pl";
{
  my (%cgi_data,  # The form data
      %cgi_cfn,   # The uploaded file(s) client-provided name(s)
      %cgi_ct,    # The uploaded file(s) content-type(s).  These are
                  #   set by the user's browser and may be unreliable
      %cgi_sfn,   # The uploaded file(s) name(s) on the server (this machine)
      $ret,       # Return value of the ReadParse call.      
      $buf        # Buffer for data read from disk.
     );

  # When writing files, several options can be set..
  # Spool the files to the /tmp directory
    $cgi_lib::writefiles = "/tmp";  
 
  # Limit upload size to avoid using too much memory
  $cgi_lib::maxdata = 5000000;

  # Start off by reading and parsing the data.  Save the return value.
 # Pass references to retreive the data, the filenames, and the content-type


  $ret = &ReadParse(\%cgi_data,\%cgi_cfn,\%cgi_ct,\%cgi_sfn);
  $val=\%cgi_data;


  # A bit of error checking never hurt anyone
  if (!defined $ret) {
    &CgiDie("Error in reading and parsing of CGI input");
  } elsif (!$ret) {
    &CgiDie("Missing parameters\n");
  } elsif (!defined $cgi_data{'upfile'} or !defined $cgi_data{'note'}) {
    &CgiDie("Data missing\n");
  }


  # Now print the page for the user to see...
  print &PrintHeader;



  print &HtmlTop("File Upload Results");

#foreach $i(sort keys %cgi_data)
#{
#print "\n $i $$val{$i}";
#}
 print <<EOT;

<p>You've uploaded a file.  Your notes on the file were:<br>
<blockquote>$cgi_data{'note'}</blockquote><br>
<p>The file has been spooled to disk as: <i>$cgi_data{'upfile'}</i><br>
The file's reported name on the client machine is:
 <i>$cgi_cfn{'upfile'}</i><br>
The file's reported Content-type (possibly none) was:
 <i>$cgi_ct{'upfile'}</i><br>
<hr>
<br>
<pre>
EOT


print "$cgi_sfn{'upfile'}";
  print "</pre>\n";

  print &HtmlBot;


  # The following lines are solely to suppress 'only used once' warnings
  $cgi_lib::writefiles = $cgi_lib::writefiles;
  $cgi_lib::maxdata    = $cgi_lib::maxdata;

}

Use commaon Cgi-lib.pl along with this file for making your program a success.
0
 
LVL 3

Author Comment

by:guadalupe
ID: 1204737
Sorry it took me so long to respond but I hve had problems getting the path for send mail because I'm only on virtual servers.  Anyway:

I got this suggestion and can't get it to work:

$msg = new MIME::Lite
                                 From    =>'info@amcintl.com',
                                 To      =>'jleidigh@movi.com.ar',
                                 Cc      =>'some@other.com, some@more.com',
                                 Subject =>'A message with 2 parts...',
                                 Type    =>'multipart/mixed';

                     # Add parts (each "attach" has same arguments as "new"):
                     attach $msg
                                 Type     =>'TEXT',
                                 Data     =>"Here's the GIF file you wanted";
                     attach $msg
                                 Type     =>'image/gif',
                                 Path     =>'../Images/',
                                 Filename =>'but1.gif';

               #  Output a message:

                     # As a string...
                     $str = $msg->as_string;

                     # To a filehandle (say, a "sendmail" stream)...
                     #$msg->print(\*SENDMAIL);

$mail_program = "/usr/lib/sendmail -t -n";

    open (MAIL, "|$mail_program") ||
      &web_error("Could Not Open Mail Program");


#
# Print the mail message to the Mail Program
# using the HERE Document method
#
    print MAIL <<__END_OF_MAIL__;
#To: jleidigh@movi.com.ar
#From: amcintl@amcintl.com
#Subject: Testmail

#$messagebody
$str
__END_OF_MAIL__

    close (MAIL);

Any suggestions.

Jason
0
 
LVL 84

Expert Comment

by:ozo
ID: 1204738
What problem did you have trying to get it to work?
0
 
LVL 3

Author Comment

by:guadalupe
ID: 1204739
The script just failed but what you see was a subtitution for a print>>eof

To:jjj
From:hhh

message

EOF

In other words the script failed at this section no some other.
0
 
LVL 3

Author Comment

by:guadalupe
ID: 1204740
Sorry here is the full sub:


sub real_send_mail {
    local($fromuser, $fromsmtp, $touser, $tosmtp,
      $subject, $messagebody) = @_;




$msg = new MIME::Lite
                                 From    =>'info@amcintl.com',
                                 To      =>'jleidigh@movi.com.ar',
                                 Cc      =>'some@other.com, some@more.com',
                                 Subject =>'A message with 2 parts...',
                                 Type    =>'multipart/mixed';

                     # Add parts (each "attach" has same arguments as "new"):
                     attach $msg
                                 Type     =>'TEXT',
                                 Data     =>"Here's the GIF file you wanted";
                     attach $msg
                                 Type     =>'image/gif',
                                 Path     =>'../Images/',
                                 Filename =>'but1.gif';

               #  Output a message:

                     # As a string...
                     $str = $msg->as_string;

                     # To a filehandle (say, a "sendmail" stream)...
                     #$msg->print(\*SENDMAIL);

# First we need to start the mail program and open
# a PIPE to the program so that anything
# we print to the filehandle, goes to the running
# program.
    open (MAIL, "|$mail_program") ||
      &web_error("Could Not Open Mail Program");

#
# Print the mail message to the Mail Program
# using the HERE Document method
#
    print MAIL <<__END_OF_MAIL__;

$msg

__END_OF_MAIL__

    close (MAIL);

#To: $touser
#From: $fromuser
#Subject: $subject
#Type: "multipart/mixed "

#attach  
#Type: "image/gif "
#Path: "../Images/"
#Filename: "but1.gif"

} #end of real_send_mail

The script just dies and I get an Internl Sever Error
All the commented junk below the close mail was just another way I tried it but I just got everthing after the to,from, sub and type  as if it were the body of the message.

Thanks

0
 
LVL 3

Author Comment

by:guadalupe
ID: 1204741
Can any one help with the last code I posted.  Sorry for the impatience but its for a job and I'm running out of time.  Thanks!
0
 
LVL 84

Expert Comment

by:ozo
ID: 1204742
you should
print MAIL $str;
not $msg, but that shouldn't cause the script to die
Do you have MIME::Lite?
Can you open ../Images/ ?

0
 
LVL 3

Author Comment

by:guadalupe
ID: 1204743
Ok I changed the print $str.  I also changed from the prin to EOF method to the one commented out $str->print(\*MAIL);  which has gotten me one step closer with this error message:

No recipient addresses found in header /dead.letter... cannot open: No such file or directory

???? I dont get it?  About /Images/ yes I have full public rights and do I have MIME:LITE, I don't know.  How do I find out??  Thanks again!!!
0
 
LVL 84

Expert Comment

by:ozo
ID: 1204744
Do you mean  $msg->print(\*MAIL); ?
0
 
LVL 3

Author Comment

by:guadalupe
ID: 1204745
Well yes but I thought as you pointed out before that it should be $str as that contains $msg in string form.  Don´t tell me in this format I needed to keep it $msg?

0
 
LVL 84

Expert Comment

by:ozo
ID: 1204746
$str is the string form, which can be interpolated
$msg is the MIME::Lite object, with ->methods
0
 
LVL 3

Author Comment

by:guadalupe
ID: 1204747
Forgive me but I had an ongoing confusion wi th "->" operator and I am also not clear on what you just said.  Can you clarify?
0
 
LVL 3

Author Comment

by:guadalupe
ID: 1204748
Oh by the way I still get the same error with:
 $msg->print(\*MAIL);

Which was:
No recipient addresses found in header /dead.letter... cannot open: No such file or directory
0
 
LVL 84

Expert Comment

by:ozo
ID: 1204749
what do you get from
print "Content-type: text/plain\n\n str is:$str\n";
0
 
LVL 3

Author Comment

by:guadalupe
ID: 1204750
Nothing.  Iput the line before and after the Mime:Lite assignment, that is after the line:
$str = $msg->as_string;
Of course befor I got the verbatum because the srting was empty but then before a print of the second occurence I got the same No recipient...
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 3

Author Comment

by:guadalupe
ID: 1204751
Still not having any luck.  Any suggestions?
0
 
LVL 84

Expert Comment

by:ozo
ID: 1204752
I'm not sure I'm following what you are doing.
What does this program do?


#!/usr/bin/perl
use MIME::Lite;
$msg = new MIME::Lite
                From    =>'info@amcintl.com',
                To      =>'jleidigh@movi.com.ar',
                Cc      =>'some@other.com, some@more.com',
                Subject =>'A message with 2 parts...',
                Type    =>'multipart/mixed';
$str = $msg->as_string;
print "Content-type: text/plain\n\n str is: $str\n";
0
 
LVL 3

Author Comment

by:guadalupe
ID: 1204753
Sorry for the delay,

I tried your program but it gave me a malformed header error.  I made a lot of changes trying to find the error.  I finally tried this out and believe that I have found the problem.

#!/usr/local/bin/perl

      # use MIME::Lite;
      $msg = "new MIME::Lite";
        #               From    =>'info@amcintl.com',
        #               To      =>'jleidigh@movi.com.ar',
         #              Cc      =>'some@other.com, some@more.com',
        #               Subject =>'A message with 2 parts...',
         #              Type    =>'multipart/mixed';
      $str = $msg->as_string;
  print "Content-type: text/html\n\n";
       print "str is: $str\n";

Even the above script gave me a malformed header error.  Then I tried commenting out the line:
    $str = $msg->as_string;
and everthing was ok.  So what do you think that says?
0
 
LVL 84

Expert Comment

by:ozo
ID: 1204754
I think it will definitely give a malformed header error with either
#use MIME::Lite; commented out, or "new MIME::Lite" quoted.
If it gives an error with
use MIME::Lite;
then it perhaps you don't have MIME::Lite installed on your system.
If you can't install it, maybe it would be easier for you to just insert the headers manually
After executing $str = $msg->as_string; $str should look like:<<'__END_OF_MAIL__'
Content-Transfer-Encoding: binary
Content-Type: multipart/mixed; boundary="_----------=_909293213199020"
MIME-Version: 1.0
X-Mailer: MIME::Lite 1.123  
From: info@amcintl.com
To: jleidigh@movi.com.ar
Cc: some@other.com, some@more.com
Subject: A message with 2 parts...

This is a multi-part message in MIME format.

--_----------=_909293213199020
Content-Disposition: inline
Content-Length: 30
Content-Transfer-Encoding: binary
Content-Type: text/plain

Here's the GIF file you wanted
--_----------=_909293213199020
Content-Disposition: inline; filename="but1.gif"
Content-Length: 512
Content-Transfer-Encoding: binary
Content-Type: image/gif; name="but1.gif"

<insert contents of ../Images here>
--_----------=_909293213199020--
__END_OF_MAIL__
Does printing that to sendmail do what you want?
0
 
LVL 3

Author Comment

by:guadalupe
ID: 1204755
I'm sorry for being dense but some of this I was unclear on.  I made this code:


     #!/usr/local/bin/perl

         $mailprog = "/bin/sendmail";
      open (MAIL, "|$mail_program");
       print MAIL<<'__END_OF_MAIL__'
       Content-Transfer-Encoding: binary
       Content-Type: multipart/mixed; boundary="_----------=_909293213199020"
       MIME-Version: 1.0
       X-Mailer: MIME::Lite 1.123  
       From: info@amcintl.com
       To: jleidigh@movi.com.ar
       Cc: some@other.com, some@more.com
       Subject: A message with 2 parts...

       This is a multi-part message in MIME format.

       --_----------=_909293213199020
       Content-Disposition: inline
       Content-Length: 30
       Content-Transfer-Encoding: binary
       Content-Type: text/plain

       Here's the GIF file you wanted
       --_----------=_909293213199020
       Content-Disposition: inline; filename="briefcse.gif"
       Content-Length: 512
       Content-Transfer-Encoding: binary
       Content-Type: image/gif; name="briefcse.gif"

       <insert contents of ../Images here>
       --_----------=_909293213199020--
       __END_OF_MAIL__

       Close (MAIL);

And still got a malformed header.  About getting it before with the commented out lines.  I went little by little but right from the start I got the Malformed header so I went commenting out lines to see if I could locate the problem.  I probably cant install mime lite because I work off a virtual server with an account.  Let me know what stupid mistake I'm making so I can hit myself.  Thanks!!!
0
 
LVL 84

Expert Comment

by:ozo
ID: 1204756
The Malformed header you got was probably
Can't find string terminator "__END_OF_MAIL__" anywhere before EOF

compiling with -Mdiagnostics gives this explaination:
    (F) Perl strings can stretch over multiple lines.  This message means that
    the closing delimiter was omitted.  Because bracketed quotes count nesting
    levels, the following is missing its final parenthesis:
   
        print q(The character '(' starts a side comment.);
   
    If you're getting this error from a here-document, you may have
    included unseen whitespace before or after your closing tag. A good
    programmer's editor will have a way to help you find these characters.

I can't tell if you have white space after your closing __END_OF_MAIL__
but it looks like you have white space in the left of it.

Also, you misspelled "close" as "Close", which would give the Malformed header
Undefined subroutine &main::Close

A -w would also warn you about
Name "main::mail_program" used only once: possible typo
   
    (W) Typographical errors often show up as unique variable names.
    If you had a good reason for having a unique name, then just mention
    it again somehow to suppress the message.  The use vars pragma is
    provided for just this purpose.
Name "main::mailprog" used only once: possible typo
Use of uninitialized value

    (W) An undefined value was used as if it were already defined.  It was
    interpreted as a "" or a 0, but maybe it was a mistake.  To suppress this
    warning assign an initial value to your variables.

Perl won't warn you about extra white space on the left of your mail headers,
but sendmail might intepret them as continuations of the previous header.

You may also want to use the sendmai -t flag

0
 
LVL 3

Author Comment

by:guadalupe
ID: 1204757
Well I don't know what to say.  I took out all the leading spaces from every line as well as trailing spaces and I changed the Close to close but I still get the malformed header response.
0
 
LVL 84

Expert Comment

by:ozo
ID: 1204758
It might help if you told us what that malformed header was.
did you
print "Content-type: text/plain\n\n";
I also notice you're missing a semicolon on the end of
print MAIL <<'__END_OF_MAIL__';
If you read the error messages that perl generates, you should have seen a warning for that too.
0
 
LVL 3

Author Comment

by:guadalupe
ID: 1204759
This is the full error that I get:
500 Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator, webmaster@connie-eastman.com.ar and inform them of the time the error occurred , and anything you might have
done that may have caused the error.

Error: HTTPd: malformed header from script /usr/local/etc/httpd/htdocs/jason/cgi-local/attach.cgi

On the missing semi colon that didn't do it.  On the standard text/plain header where is it supposed to be printed?  What does it have to do with the mail portion of the prog.
After the close Mail I did a standard html header just to see if it got there but no go.
Sorry this is so on going but thank you again.  


0
 
LVL 84

Expert Comment

by:ozo
ID: 1204760
Does the server on connie-eastman.com.ar keep an error log of the error messages perl would produce when it tries to run a program?
Can you run your perl program directly from a shell prompt to test it?
Either of thise may help make it easier to find the problem.
perhaps we should start with something more basic.
Can you get this program to work:

#!/usr/local/bin/perl
print "Content-type text/plain\n\n";
print "test";

0
 
LVL 3

Author Comment

by:guadalupe
ID: 1204761
On the eror log, I don't know if I can get access as its a virtual server which greatly limits my access.  Which should also answer you question about running directly from a shell prompt.  I have no telnet access only ftp and only to a virtual root directory.  About more simple programs working...
This is an attempt at modifying a standard forms processor program.  The standard version gives the option to process form info and place it in a flat text file or e-mail it.  I have already successfully set up all the normal features and had thme running.  My goal is to allow the e-mailing of the flat text file(for direct import into a data base) on a time lapsd or entries added bases.  I already have the code for determining if a specified time has passed or to check on the number of entries.  This is fairly straight forward code.  But this detail of attaching a file to mail has me stumped.  Anyway the short answer is that the program: print html header, print test works.
I'll check on the error log and get bck to you, thanks.
0
 
LVL 3

Author Comment

by:guadalupe
ID: 1204762
Ok no word back on the error log but my feeling is its a no.  What about installing lite.pm  I got it of the web but I'm affraid that since I have no access to a command line and therefore can't use makefile that I will be unable to use it.  If I "push" a folder where it is and then  "use lite" then follow with the pold script $msg = new MIME::Lite   do you think that will work?
0
 
LVL 84

Expert Comment

by:ozo
ID: 1204763
That should work.
@INC may already contain '.', so just installing the module in the same directory may work.
Just to be sure I understans what's working for you and what's not Could you tell me what this does?

#!/usr/local/bin/perl
BEGIN{
  print "Content-type: text/plain\n\n";
  $|=1;
  open(STDERR, ">&STDOUT");
  push @INC,'myinstalldirectory';
}
open(MAIL, "|/bin/sendmail -t 2>&1") or warn "error opening pipe : $!";
print MAIL "To: jleidigh\@movi.com.ar\nSubject: test\n\nmessage\n" or warn "print: $!";
close MAIL or warn "close:$! $?";
print "done\n";

0
 
LVL 3

Author Comment

by:guadalupe
ID: 1204764
Iget the same error as before.
I also tried to do what I suggested which is push lite.pm and use lite but I got the same error as well

Error: HTTPd: malformed header from script /usr/local/etc/httpd/htdocs/jason/cgi-local/test4.cgi
0
 
LVL 84

Expert Comment

by:ozo
ID: 1204765
How about this

#!/usr/local/bin/perl
print "Content-type text/plain\n\n";
print "$]\n@INC\n$ENV{SERVER_SOFTWARE}\n";
0
 
LVL 3

Author Comment

by:guadalupe
ID: 1204766
Same error as before.

Error: HTTPd: malformed header from script /usr/local/etc/httpd/htdocs/jason/cgi-local/test5.cgi

You gotta hate me by now.
0
 
LVL 84

Expert Comment

by:ozo
ID: 1204767
Can you show us a program that doesn't give that error?
0
 
LVL 3

Author Comment

by:guadalupe
ID: 1204768
Ok Ladies and Gents,

Prepare to be astounded and emazed. The short asnswer to your question is no.  I was trying to show you something but of course make it a little small.  As I said before, I have the entire Form_Processor (from Selena Sol) up and running.  However every time we talked about doing changes or script ideas I would write a seperate script.  This was to avoid errors from other places that would be a pain to track down.  So instead I just wrote little new scripts.  Anyway after your lst comment I experimented and found I could even get this to run:

#!/usr/local/bin/perl

 print "Content-type: text/html\n\n";
 print "test done";

Yet the shebang statement is the same used in the form processor which actually runs two seperate scripts as well as requireing libraries and blah blah blah.  So I started expeimenting.  No matter where I put the scripts (within the cgi folder/subfolders) they wouldn't run.  Then I tried editing the Form Procesor and low and behold it would run edits and all.  Soooooo I just edited the mail-lib.pl to do attaches and it seems to work.  I don't actually get the file though it says it is attached but I believe that is just a problemwith the path. Can I use relative paths with Mime:Lite?

Anyway I'm not out of the woods yet.  Can anyone explain to me what the problem is?  Why can't I add new scripts? I did with the Form Processor.  That was not there before.  It is not a chmod issue as I always changed permissions on test files and directories to 777 just to be sure.   ?????????????????
Signed Confused
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Suggested Solutions

On Microsoft Windows, if  when you click or type the name of a .pl file, you get an error "is not recognized as an internal or external command, operable program or batch file", then this means you do not have the .pl file extension associated with …
Many time we need to work with multiple files all together. If its windows system then we can use some GUI based editor to accomplish our task. But what if you are on putty or have only CLI(Command Line Interface) as an option to  edit your files. I…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now