+
+ push @to, $options{bcc} if defined($options{bcc});
+ local $@; # just in case
+ eval { sendmail($message, { transport => $transport,
+ from => $options{from},
+ to => \@to }) };
+
+ my $error = '';
+ if(ref($@) and $@->isa('Email::Sender::Failure')) {
+ $error = $@->code.' ' if $@->code;
+ $error .= $@->message;
+ }
+ else {
+ $error = $@;
+ }
+
+ # Logging
+ if ( $conf->exists('log_sent_mail') and $options{'custnum'} ) {
+ my $cust_msg = FS::cust_msg->new({
+ 'env_from' => $options{'from'},
+ 'env_to' => join(', ', @to),
+ 'header' => $message->header_as_string,
+ 'body' => $message->body_as_string,
+ '_date' => $time,
+ 'error' => $error,
+ 'custnum' => $options{'custnum'},
+ 'msgnum' => $options{'msgnum'},
+ 'status' => ($error ? 'failed' : 'sent'),
+ });
+ $cust_msg->insert; # ignore errors
+ }
+ $error;
+
+}
+
+=item generate_email OPTION => VALUE ...
+
+Options:
+
+=over 4
+
+=item from
+
+Sender address, required
+
+=item to
+
+Recipient address, required
+
+=item bcc
+
+Blind copy address, optional
+
+=item subject
+
+email subject, required
+
+=item html_body
+
+Email body (HTML alternative). Arrayref of lines, or scalar.
+
+Will be placed inside an HTML <BODY> tag.
+
+=item text_body
+
+Email body (Text alternative). Arrayref of lines, or scalar.
+
+=item custnum, msgnum (optional)
+
+Customer and template numbers, passed through to send_email for logging.
+
+=back
+
+Constructs a multipart message from text_body and html_body.
+
+=cut
+
+#false laziness w/FS::cust_bill::generate_email
+
+use MIME::Entity;
+use HTML::Entities;
+
+sub generate_email {
+ my %args = @_;
+
+ my $me = '[FS::Misc::generate_email]';
+
+ my @fields = qw(from to bcc subject custnum msgnum);
+ my %return;
+ @return{@fields} = @args{@fields};
+
+ warn "$me creating HTML/text multipart message"
+ if $DEBUG;
+
+ $return{'nobody'} = 1;
+
+ my $alternative = build MIME::Entity
+ 'Type' => 'multipart/alternative',
+ 'Encoding' => '7bit',
+ 'Disposition' => 'inline'
+ ;
+
+ my $data;
+ if ( ref($args{'text_body'}) eq 'ARRAY' ) {
+ $data = join("\n", @{ $args{'text_body'} });
+ } else {
+ $data = $args{'text_body'};
+ }
+
+ $alternative->attach(
+ 'Type' => 'text/plain',
+ 'Encoding' => 'quoted-printable',
+ #'Encoding' => '7bit',
+ 'Data' => $data,
+ 'Disposition' => 'inline',
+ );