+sub write_down_message {
+ use File::Temp qw(tempfile);
+
+ local $@;
+ my ($fh, $filename) = eval { tempfile() };
+ if ( !$fh || $@ ) {
+ print STDERR "$0: Couldn't create temp file, using memory\n";
+ print STDERR "error: $@\n" if $@;
+
+ my $message = \do { local (@ARGV, $/); <> };
+ unless ( $$message =~ /\S/ ) {
+ print STDERR "$0: no message passed on STDIN\n";
+ exit 0;
+ }
+ $$message = $opts{'headers'} . $$message if $opts{'headers'};
+ return ( content => $message );
+ }
+
+ binmode $fh;
+ binmode \*STDIN;
+
+ print $fh $opts{'headers'} if $opts{'headers'};
+
+ my $buf; my $empty = 1;
+ while(1) {
+ my $status = read \*STDIN, $buf, BUFFER_SIZE;
+ unless ( defined $status ) {
+ print STDERR "$0: couldn't read message: $!\n";
+ exit EX_TEMPFAIL;
+ } elsif ( !$status ) {
+ last;
+ }
+ $empty = 0 if $buf =~ /\S/;
+ print $fh $buf;
+ };
+ close $fh;
+
+ if ( $empty ) {
+ print STDERR "$0: no message passed on STDIN\n";
+ exit 0;
+ }
+ print STDERR "$0: temp file is '$filename'\n" if $opts{'debug'};
+ return (filename => $filename);
+}
+