+=head2 create_mime_message
+
+ create_mime_message([To=>'don@debian.org'],$body,[$attach1, $attach2],$include_date);
+
+Creates a MIME encoded message with headers given by the first
+argument, and a message given by the second.
+
+Optional attachments can be specified in the third arrayref argument.
+
+Whether to include the date in the header is the final argument; it
+defaults to true, setting the Date header if one is not already
+present.
+
+Headers are passed directly to MIME::Entity::build, the message is the
+first attachment.
+
+Each of the elements of the attachment arrayref is attached as an
+rfc822 message if it is a scalar or an arrayref; otherwise if it is a
+hashref, the contents are passed as an argument to
+MIME::Entity::attach
+
+=cut
+
+sub create_mime_message{
+ my ($headers,$body,$attachments,$include_date) = @_;
+ $attachments = [] if not defined $attachments;
+ $include_date = 1 if not defined $include_date;
+
+ die "The first argument to create_mime_message must be an arrayref" unless ref($headers) eq 'ARRAY';
+ die "The third argument to create_mime_message must be an arrayref" unless ref($attachments) eq 'ARRAY';
+
+ if ($include_date) {
+ my %headers = apply {defined $_ ? lc($_) : ''} @{$headers};
+ if (not exists $headers{date}) {
+ push @{$headers},
+ ('Date',
+ strftime("%a, %d %b %Y %H:%M:%S +0000",gmtime)
+ );
+ }
+ }
+
+ # Build the message
+ # MIME::Entity is stupid, and doesn't rfc1522 encode its headers, so we do it for it.
+ my $msg = MIME::Entity->build('Content-Type' => 'text/plain; charset=utf-8',
+ 'Encoding' => 'quoted-printable',
+ (map{encode_rfc1522(encode_utf8(defined $_ ? $_:''))} @{$headers}),
+ Data => encode_utf8($body),
+ );
+
+ # Attach the attachments
+ for my $attachment (@{$attachments}) {
+ if (ref($attachment) eq 'HASH') {
+ $msg->attach(%{$attachment});
+ }
+ else {
+ # This is *craptacular*, but because various MTAs
+ # (sendmail and exim4, at least) appear to eat From
+ # lines in message/rfc822 attachments, we need eat
+ # the entire From line ourselves so the MTA doesn't
+ # leave \n detrius around.
+ if (ref($attachment) eq 'ARRAY' and $attachment->[1] =~ /^From /) {
+ # make a copy so that we don't screw up anything
+ # that is expecting this arrayref to stay constant
+ $attachment = [@{$attachment}];
+ # remove the from line
+ splice @$attachment, 1, 1;
+ }
+ elsif (not ref($attachment)) {
+ # It's a scalar; remove the from line
+ $attachment =~ s/^(Received:[^\n]+\n)(From [^\n]+\n)/$1/s;
+ }
+ $msg->attach(Type => 'message/rfc822',
+ Data => $attachment,
+ Encoding => '7bit',
+ );
+ }
+ }
+ return $msg->as_string;