Sending a text mail

Top Japanese page




Overview

Send a text mail using sendmail.

Flow

  1. Load Jcode
  2. Setup properly
  3. Set mail contents
  4. Set mail header
  5. Send a mail
  6. Display a completion message

A sample code

 use Jcode;
 
 my $to_mail = 'tomail@dummy.com';
 my $from_mail = 'frommail@dummy.com';
 my $subject = 'Text mail';
 my $mail_cmd = 'sendmail -t';
 
 my $contents = '
 This is a text mail.
 This contents will be included in the mail.
 Usually this part is passed from a html form.
 ';
 
 $contents = jcode($contents)->jis;
 
 my $header;
 $header = "From: " . jcode("$from_mail")->mime_encode . "\n";
 $header .= "To: " . jcode("$to_mail")->mime_encode . "\n";
 $header .= "Subject: " . jcode($subject)->mime_encode . "\n";
 $header .= "MIME-Version: 1.0\n";
 $header .= "Content-type: text/plain; charset=ISO-2022-JP\n";
 $header .= "Content-Transfer-Encoding: 7bit\n\n";
 
 if (open(SMAIL, "| $mail_cmd")){
        print SMAIL $header;
        print SMAIL $contents;
        close(SMAIL);
 } else {
        &error("Cannot send the mail<br>Check $mail_cmd");
 }
 
 prnit "Content-Type: text/html\n\n";
 print "Completed to send";

Explanation of the code

 use Jcode;

Load Jcode.

 my $to_mail = 'tomail@dummy.com';
 my $from_mail = 'frommail@dummy.com';
 my $subject = 'Text mail';
 my $mail_cmd = 'sendmail -t';
 
 my $contents = '
 This is a text mail.
 This contents will be included in the mail.
 Usually this part is passed from a html form.
 ';

This is mail contents. Usually passed from a mail from of an HTML page.

 $contents = jcode($contents)->jis;

Convert contents to JIS. This is not necessarily to be JIS. Just need to match with header encode.

 my $header;
 $header = "From: " . jcode("$from_mail")->mime_encode . "\n";
 $header .= "To: " . jcode("$to_mail")->mime_encode . "\n";
 $header .= "Subject: " . jcode($subject)->mime_encode . "\n";

Specify the headers. In thsi example, put them into a variable. Using jcode()->mime_encode, encoding the headers. This allows to send proper Japanese code through email.

 $header .= "MIME-Version: 1.0\n";
 $header .= "Content-type: text/plain; charset=ISO-2022-JP\n";
 $header .= "Content-Transfer-Encoding: 7bit\n\n";

This part is also header. Since Content-type is text/plain, the contents is treated as plain text. Charset is treated as JIS. The header is finished by the last two new-line codes.

 if (open(SMAIL, "| $mail_cmd")){
        print SMAIL $header;
        print SMAIL $contents;
        close(SMAIL);
 } else {
        &error("Cannot send the mail<br>Check $mail_cmd");
 }

Send the mail here.

 prnit "Content-Type: text/html\n\n";
 print "Completed to send";

If necessary, display the completion message.