#!/usr/bin/perl

BEGIN { use lib '/usr/home/cfg' ; require push_inc ; }

use MIME::Lite;
use Mail::Sendmail;
    
require cfg ;

print "Content-type: text/html\n\n";

&today ;

our $debug = 1 ;

#------------------------------------------------------------------------------------------

# https://itvadmin.co.za/cgi-bin/scripts/admin/oneoff/sendmail.pl

use CGI::Carp qw(fatalsToBrowser);

$email_add{'reply-to'}        = 'info@telemedia.co.za' ;

# &mailsend('','rory@mathew.za.net',"mailsend ffwaybill Test $now_year-$now_mm-$now_dd",'test email') ;

# &common_mailsend_sendgrid('text','rory@kre8it.co.za','TEST - Tue 30-Apr-2024','Hi Rory Mathew<br><br>TEST AT 14:00 <br><br><br><br><br><br><br><br><br>Please let me know if you need anything. <br><br>Thanks,<br>Rory Mathew','/var/www/html/pdf/feed_details','Feed_Details-1003.pdf','Test Events','events@interactivetvafrica.com','','rory@kre8it.co.za','','') ;
# &common_mailsend_sendgrid('text','rory@kre8it.co.za','TEST - Tue 30-Apr-2024','testing 123','/var/www/html/pdf/event_details','Event_Details-5136.pdf','ITV Africa Events','events@itvadmin.co.za','','','',0) ;
&mailsend_sendgrid('text','rory@kre8it.co.za','TEST - Tue 30-Apr-2024','testing 123','/var/www/html/pdf/event_details','Event_Details-5136.pdf','Telemedia Events','website@bookingtelemedia.co.za','','','',0) ;
# &common_send_mail('rory@kre8it.co.za','','','','','test msg','TEST - Tue 30-Apr-2024') ;

exit ;

#------------------------------------------------------------------------------------------

sub mailsend_sendgrid {
   
   local ($qtype,$qemail,$qsubject,$qbody,$qattachfilepath,$qattachfilename,$qfromname,$qfromemail,$qccemail,$qbccemail,$uploaded_doc,$operator_email) = @_;
   
   $qccemail =~ s/\;/\,/g ;
   $qbccemail =~ s/\;/\,/g ;

   use Email::SendGrid::V3;
   
   &common_debug("common_mailsend_sendgrid [$qtype,$qemail,$qsubject,$qbody,$qattachfilepath,$qattachfilename,$qfromname,$qfromemail,$qccemail,$qbccemail,$uploaded_doc,$operator_email]") ;

     #=======================
     #REF1: https://docs.sendgrid.com/for-developers/sending-email/curl-examples
     #REF2: https://github.com/GrantStreetGroup/Email-SendGrid-V3
     #To Install: 
     #cpan -i Email::SendGrid::V3
     #cd /root/perl5/lib/perl5
     #cp -R Email /usr/local/lib64/perl5
     #=======================

   my $sg = Email::SendGrid::V3->new(api_key => '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');

   $qbody =~ s/'/`/gi;
   $qbody =~ s/\r//gi;
   $qbody =~ s/\n//gi;

   #------------------------------------------------
   #SEND TEXT ONLY MAIL 
   if ($qtype eq "text") {
	   
	   # , cc => [ $qccemail ], bcc => [ $qbccemail ] 
	   
	   	my %cc_args  = ($qccemail)  ? (cc => [ "$qccemail" ]) : () ;
		my %bcc_args = ($qbccemail) ? (bcc => [ "$qbccemail" ]) : () ;

		my $result = $sg->from($qfromemail,$qfromname)
					  ->reply_to($email_add{'reply-to'}, "$useropts{short} Events")
                      ->subject($qsubject)
                      ->add_content('text/plain', $qbody)
                      ->add_envelope( to => [ "$qemail" ], %cc_args, %bcc_args)
                      ->send;

      $qres = $result->{success} ? "success" : "error: " . $result->{reason};

   }

   #------------------------------------------------
   #SEND HTML ONLY MAIL 
   if ($qtype eq "html") {

		$qbody = qq~<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Film Freight</title>
<style type="text/css"> .font { font-family: Tahoma, Geneva, sans-serif; } .font { font-size: 12px; }</style>
</head>
<body>
<p>
<img alt="" src="https://$ENV{SERVER_NAME}/img/email_logo.jpg" border="0">
</p>
<p>
$qbody
</p>
<br />
<br />
</body>
</html>
~;     
		my %cc_args  = ($qccemail)  ? (cc => [ "$qccemail" ]) : () ;
		my %bcc_args = ($qbccemail) ? (bcc => [ "$qbccemail" ]) : () ;
	  
		my $result = $sg->from($qfromemail,$qfromname)
					  ->reply_to($email_add{'reply-to'}, "$useropts{short} Feeds")
					  ->subject($qsubject)
					  ->add_content('text/html', $qbody)
					  ->add_envelope( to => [ "$qemail" ], %cc_args, %bcc_args)
					  ->send;

		$qres = $result->{success} ? "success" : "error: " . $result->{reason};

   }  

   #------------------------------------------------
   #SEND HTML WITH ATTACHMENT MAIL 
   if ($qtype eq "htmlattach") {
	  
	  my $encodedcontent = &encode_attachment("$qattachfilepath/$qattachfilename");

      my %args = ( 
              type   => 'AUTO', 
              disposition => 'attachment' 
          );
		  
		  $qbody = qq~<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Film Freight</title>
<style type="text/css"> .font { font-family: Tahoma, Geneva, sans-serif; } .font { font-size: 12px; }</style>
</head>
<body>
<p>
<img alt="" src="https://$ENV{SERVER_NAME}/img/email_logo.jpg" border="0">
</p>
<p>
$qbody
</p>
<br />
<br />
</body>
</html>
~;     
		
		my @attachments = ($qattachfilename, $encodedcontent, %args) ;
		
		if ($uploaded_doc) {
			my $encodedcontent = &encode_attachment("$uploaded_doc") ;
			push @attachments, ($uploaded_doc, $encodedcontent, %args) ;
		}
		
		# if ($operator_email) {
			# my $encodedcontent = &encode_attachment("$htmlpath/pdf/operator_flyer") ;
			# push @attachments, ("operator_email_attach.pdf", $encodedcontent, %args) ;
		# }

		
		my %cc_args  = ($qccemail)  ? (cc => [ "$qccemail" ]) : () ;
		my %bcc_args = ($qbccemail) ? (bcc => [ "$qbccemail" ]) : () ;
					  
		my $result = $sg->from($qfromemail,$qfromname)
			->reply_to($email_add{'reply-to'}, "$useropts{short} Feeds")
			->subject($qsubject)
			->add_content('text/html', $qbody)
			->add_attachment(@attachments)
			->add_envelope( to => [ "$qemail" ], %cc_args, %bcc_args)
			->send;
					  
		$qres = $result->{success} ? "success" : "error: " . $result->{reason};   

      #NOTE: Cannot use command line cURL here as the body (base64 pdf) is too large - below works for smaller content
      #$qres = `/usr/bin/curl --request POST --url https://api.sendgrid.com/v3/mail/send --header 'authorization: Bearer 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' --header 'Content-Type: application/json' --data '{"personalizations": [{"to": [{"email": "$qemail"}]}],"from": {"email": "no-reply\@myappointment.co.za"},"subject":"$qsubject","content": [{"type": "text/html","value": "$qbody"}], "attachments": [{"content": "$encodedcontent", "type": "text/plain", "filename": "$qattachfilename"}]}'`;
   }  
   #------------------------------------------------
   
   &common_debug("common_mailsend_sendgrid [$qres]") ;

   return "$qres";

} #------------------------------------------------------------------------------------------

# sub SendEmailSendgrid {
   
   # local($qtype,$qemail,$qsubject,$qbody,$qattachfilepath,$qattachfilename,$qfromname,$qfromemail) = @_;

   # use Email::SendGrid::V3;

     # #=======================
     # #REF1: https://docs.sendgrid.com/for-developers/sending-email/curl-examples
     # #REF2: https://github.com/GrantStreetGroup/Email-SendGrid-V3
     # #To Install: 
     # #cpan -i Email::SendGrid::V3
     # #cd /root/perl5/lib/perl5
     # #cp -R Email /usr/local/lib64/perl5
     # #=======================

   # my $sg = Email::SendGrid::V3->new(api_key => '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');

   # $qbody =~ s/'/`/gi;
   # #$qbody =~ s/"/\\\"/gi;
   # $qbody =~ s/\r//gi;
   # $qbody =~ s/\n//gi;

   # #------------------------------------------------
   # #SEND TEXT ONLY MAIL 
   # if ($qtype eq "text") {

      # my $result = $sg->from($qfromemail,$qfromname)
					  # ->reply_to('filmfreight@filmfreight.co.za', 'Film Freight')
                      # ->subject($qsubject)
                      # ->add_content('text/plain', $qbody)
                      # ->add_envelope( to => [ $qemail ] )
                      # ->send;

      # $qres = $result->{success} ? "success" : "error: " . $result->{reason};

   # }

   # #------------------------------------------------
   # #SEND HTML ONLY MAIL 
   # if ($qtype eq "html") {

		# $qbody = qq~<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
# <html xmlns="http://www.w3.org/1999/xhtml">
# <head>
# <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
# <title>Untitled Document</title>
# <style type="text/css"> .font { font-family: Tahoma, Geneva, sans-serif; } .font { font-size: 12px; }</style>
# </head>
# <body>
# <p>
# <img alt="" src="https://$ENV{SERVER_NAME}/img/email_logo.jpg" border="0">
# </p>
# <p>
# $qbody
# </p>
# <br />
# <br />
# </body>
# </html>
# ~;     
	  
		# my $result = $sg->from($qfromemail,$qfromname)
					  # ->reply_to('filmfreight@filmfreight.co.za', 'Film Freight')
					  # ->subject($qsubject)
					  # ->add_content('text/html', $qbody)
					  # ->add_envelope( to => [ $qemail ] )
					  # ->send;

		# $qres = $result->{success} ? "success" : "error: " . $result->{reason};

   # }  

   # #------------------------------------------------
   # #SEND HTML WITH ATTACHMENT MAIL 
   # if ($qtype eq "htmlattach") {

      # use MIME::Base64 qw(encode_base64);

      # open (infile, "$qattachfilepath/$qattachfilename");
          # binmode infile;
          # while (<infile>) {
             # #$_ =~ s/\r//gi;
             # #$_ =~ s/\n//gi;
             # $myfilecontents .= "$_";
          # }
      # close(infile);

      # $encodedcontent = encode_base64($myfilecontents);

      # $encodedcontent =~ s/'/`/gi;
      # #$encodedcontent =~ s/"/\\\"/gi;
      # $encodedcontent =~ s/\r//gi;
      # $encodedcontent =~ s/\n//gi;

      # my %args = ( 
              # type   => 'text/plain', 
              # disposition      => 'attachment' 
          # );

      # my $result = $sg->from($qfromemail,$qfromname)
					  # ->reply_to('filmfreight@filmfreight.co.za', 'Film Freight')
                      # ->subject($qsubject)
                      # ->add_content('text/html', $qbody)
                      # ->add_attachment($qattachfilename, $encodedcontent, %args)
                      # ->add_envelope( to => [ $qemail ] )
                      # ->send;

      # $qres = $result->{success} ? "success" : "error: " . $result->{reason};

      # #NOTE: Cannot use command line cURL here as the body (base64 pdf) is too large - below works for smaller content
      # #$qres = `/usr/bin/curl --request POST --url https://api.sendgrid.com/v3/mail/send --header 'authorization: Bearer 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' --header 'Content-Type: application/json' --data '{"personalizations": [{"to": [{"email": "$qemail"}]}],"from": {"email": "no-reply\@myappointment.co.za"},"subject":"$qsubject","content": [{"type": "text/html","value": "$qbody"}], "attachments": [{"content": "$encodedcontent", "type": "text/plain", "filename": "$qattachfilename"}]}'`;
   # }  
   # #------------------------------------------------

   # #log all mail sends here
 
   # # $datetime = `date "+%Y-%m-%d %H:%M"`;
   # # chop($datetime);

   # # open (logfile, ">> $basedir/admin/SendGrid.log");
      # # print logfile "$datetime	$qtype	$qemail	$qsubject	$qattachfilename	$qfromname	$qfromemail	$qres\n";
   # # close(logfile);


   # return "$qres";

# } #------------------------------------------------------------------------------------------

# sub smtp_mail_auth {

# my ($to,$cc,$email_bcc,$email_subject,$email_message,$html,$thead) = @_ ;

# return unless $email_message ;
# return unless $email_subject ;

# use Time::HiRes qw( gettimeofday );
# use MIME::Lite;
# use Net::SMTP_auth;

# my $email_from              = $user ;

# $email_to                   = ($to) ? $to : $email_from ;
# $email_to                   =~ s/\s+//; # Strip out any whitespace

# my ($s, $usec)              = gettimeofday();

# my $email_message_id        = "<$s$usec\@mailserver.filmfreight.co.za>" ;
# my $email_mailed_by         = "filmfreight.co.za" ;
# my $email_from_display      = qq("$sig ($email_from_prefix) ($ibookref)" <$email_from>) ;

# $msg = MIME::Lite -> new(
   # 'Message-ID'   => $email_message_id,
   # 'Mailed-By:'   => $email_mailed_by,
   # 'From'         => $email_from_display,
   # 'To'           => $email_to,
   # 'Bcc'          => $email_bcc,
   # 'Subject'      => $email_subject,
   # 'Type'         => 'multipart/mixed'
# );

# $msg -> attach(
   # 'Type'         => 'text/plain',
   # 'Data'         => $email_message
# );

# my $email         = $msg -> as_string();

# my $smtp_host = 'filmfreight-co-za.mail.protection.outlook.com';
# my $smtp_port = 25;

# my $smtp = Net::SMTP_auth -> new ($smtp_host, Port=>$smtp_port) or die "Can't connect";

# # $smtp->auth('NORMAL', $email_from, 'Roq80545')  or die "Error:" . $smtp->message();
# $smtp->auth('OAuth2', $email_from, 'Roq80545')    or die "Error:" . $smtp->message();
# # $smtp->auth('AUTH', $user, $pass)               or die "Error:" . $smtp->message();

# # die "Couldn't login: $!" unless \&auth;

# $smtp->mail($email_from)                          or die "Error:" . $smtp->message();
# $smtp->recipient(split(/;/, $email_to));
# $smtp->data()                                     or die "Error:" . $smtp->message();
# $smtp->datasend($email)                           or die "Error:" . $smtp->message();
# $smtp->dataend()                                  or die "Error:" . $smtp->message();
# $smtp->quit                                       or die "Error:" . $smtp->message();
						                         
# } #------------------------------------------------------------------------------------------

# sub auth {
	
	# my $sasl;
	# my $mechanisms =  ['AUTH', 500];
    
	# my $sasl = Authen::SASL->new(
        # mechanism => $mechanisms,
        # debug => 1, 
        # callback => { 
            # user => $user, 
            # pass => $pass, 
            # authname => $user,
        # } 
    # );
	
# } #------------------------------------------------------------------------------------------

# sub smtp_mail {

# my ($to,$cc,$bcc,$subj,$msg,$html,$thead) = @_ ;

# return unless $msg ;
# return unless $subj ;

# # use Mail::Sendmail;

# $to = $user unless $to ;

# # use Net::SMTP 3.0;
# # Force use of Authen::SASL::Perl - it may fix problems with other alternatives
# # use Authen::SASL qw(Perl);

# # Port        => "587", 
# # doSSL       => "starttls",
# # SSL_version => "TLSv1_1", 
# # Debug       => 4

# use Net::SMTPS;

# my $smtp = Net::SMTPS->new("filmfreight-co-za.mail.protection.outlook.com", Port => 25); die "Initialization failed: $!" if !defined $smtp;

# my $sender   = $user ;
# print "Trying to authenticate..";
# # $smtp->auth('OAuth2', $user, $pass) or die "could not authenticate : $!\n";

# &auth or die "Couldn't login: $!" ;

# my $receiver = $to;
# $smtp->mail( $sender );
# $smtp->to( $receiver );
# $smtp->data()                                       or die "Error:" . $smtp->message();
# $smtp->datasend( "To: $receiver\n" )                or die "Error:" . $smtp->message();
# $smtp->datasend( "From: $sender\n" )                or die "Error:" . $smtp->message();
# $smtp->datasend( "Content-Type: text/html\n" )      or die "Error:" . $smtp->message();
# $smtp->datasend( "Subject: Testing Net::SMTP" )     or die "Error:" . $smtp->message();
# $smtp->datasend( "\n" )                             or die "Error:" . $smtp->message();
# $smtp->datasend( 'The body of the email' )          or die "Error:" . $smtp->message();
# $smtp->dataend()                                    or die "Error:" . $smtp->message();
# $smtp->quit()                                       or die "Error:" . $smtp->message();
	
# } #------------------------------------------------------------------------------------------


# sub smtp_tls_mail {

# my ($to,$cc,$bcc,$subj,$msg,$html,$thead) = @_ ;

# return unless $msg ;
# return unless $subj ;

# my $user = 'pod@filmfreight.co.za' ;

# $to = $user unless $to ;

# use Net::SMTP::TLS;  

# my $mailer = new Net::SMTP::TLS(  
    # # 'smtp.office365.com',
    # # 'mail.protection.outlook.com',
    # # 'o365info-com.mail.protection.outlook.com',
    # 'filmfreight-co-za.mail.protection.outlook.com',
    # # Port      => 587,  
    # Port        => 25,  
    # Hello       => '',
    # User        => "$user",
	# # SSL_version => "TLSv1_2", 
    # Password    => 'Roq80545',
    # Debug       => 1) || die "Cannot connect to smtp server";
 
# $mailer->mail($user);
# $mailer->to($to);
# $mailer->data;  
# $mailer->datasend("\n");  
# $mailer->datasend("Sent from perl!");  
# $mailer->dataend;  
# $mailer->quit;
	
# } #------------------------------------------------------------------------------------------

# sub smtp_mail_1 {

# my ($to,$cc,$bcc,$subj,$msg,$html,$thead) = @_ ;

# use Mail::Sendmail;

# $to = $user unless $to ;

# my %mail = () ;

# %mail = (
		 # smtp             => 'localhost',
		 # From             => $user,
		 # To               => $to,
		 # Cc               => $cc,
		 # Bcc              => $bcc,
		 # Subject          => $subj
		 # );

# $mail{smtp}               = "smtp.afrihost.co.za";
# $mail{port}               = 25;
# $mail{Auth}               = {user => $user, pass => 'PvB{Da{8($ow'};
# $mail{body}               = <<END_OF_BODY;
# $msg
# END_OF_BODY

# if ($html) {
	# my $boundary          = "====" . time() . "====";
	# $mail{'content-type'} = "multipart/alternative; boundary=\"$boundary\"";
	# $boundary             = '--'.$boundary;
	# $mail{body}           = <<END_OF_BODY;
# $boundary
# Content-Type: text/html; charset=ISO-8859-1
# Content-Transfer-Encoding: 7bit
# <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
# <html>
# <head>
# <meta content="text/html;charset=ISO-8859-1" http-equiv="Content-Type">
# <title></title>
# </head>
# <body>
# <p>
# <img alt="" src="https://$ENV{SERVER_NAME}/img/email_logo.jpg" border="0">
# </p>
# <p>
# $msg
# </p>
# </body>
# </html>

# $boundary--

# END_OF_BODY

# }

# sendmail(%mail) ;
	
# } #------------------------------------------------------------------------------------------

use today ;
use common ;
# use mailsend ;

1;