Search code examples
perlemailmime

Perl email script--content encoding issue


I decided to dive into perl with some of the starter scripts on their site. I started with http://learn.perl.org/examples/email.html to try a basic email sending script.

Here's the actual code:

#!/usr/bin/perl
use strict;
use warnings;

#Character encoding var
my $encoding='text/plain; charset="iso-8859-5"';

#Create the message
use Email::MIME;
my $message = Email::MIME->create(
        header_str => [
                From => 'gmail@gmail.com',
                To => 'gmail2@gmail.com',
                Subject => 'I sent you this message using Perl.',
        ],
        body_str => 'I sent you this message using Perl.  One of those languages that would\' would\'ve been helpful much sooner in my life...',
        );
use Email::Sender::Simple qw(sendmail);
sendmail($message);

What I get when I do perl script.pl is an error message of

body_str was given, but no charset is defined at /usr/local/share/perl/5.10.1/Email/MIME.pm line 243
    Email::MIME::create('Email::MIME', 'header_str', 'ARRAY(0x9a04818)', 'body_str', 'I sent you this message using Perl.  One ...') called at script.pl line 10

I did some searching around the Email::MIME module and found the body_str section but it didn't shed any light on the error message. I'm assuming I need to set the encoding but I'm not sure how to go about doing it.


Solution

  • If you have a look at the SYNOPSIS section of the docs, you'll see that you can also pass an "attributes" hashref to create(). You can define charset here. You may also find that you'll need to define encoding here as well. For example, you could do:

    my $message = Email::MIME->create(
        header_str => [
                From    => 'gmail@gmail.com',
                To      => 'gmail2@gmail.com',
                Subject => 'I sent you this message using Perl.',
        ],
        attributes => {
            encoding => 'quoted-printable', 
            charset  => "US-ASCII",
        },
        body_str => 'I sent you this message using Perl.  One of those languages that would\' would\'ve been helpful much sooner in my life...',
    );