How i can resend mail by php from php://stdin with replace subjet to alias

63 Views Asked by At

I try use php script for get message, get alias and replace subject on that alias, then send.

Postfix configuration master.cf

etof  unix  -       n       n       -       10      pipe   flags=Rq user=sgadmin null_sender=   argv=/home/admin/emailtofile5.php -e live -f ${sender} -t ${recipient}

transport

srv-postrelaytosms-01.local etof:

main.cf

smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
biff = no
append_dot_mydomain = no
readme_directory = no
compatibility_level = 3.6
smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
smtpd_tls_security_level=may
smtp_tls_CApath=/etc/ssl/certs
smtp_tls_security_level=may
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
myhostname = srv-postrelaytosms-01.gurman.local
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = /etc/mailname
mydestination = srv-postrelaytosms-01.local, srv-postrelaytosms-01, localhost.localdomain, localhost
relayhost =
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
inet_protocols = all
transport_maps = hash:/etc/postfix/transport
virtual_alias_maps = hash:/etc/postfix/virtual_aliases

virtual_aliases

@srv-postrelaytosms-01.local   [email protected]

I have installed php-cli, composer, phpmailer, ZBateson\MailMimeParser. Yea, i'm trying a lot. If i use script (find in internet)

    <?php
    // See what options are passed in and absorb them:
    $opts=getopt('e:f:t:h');

    // Open the output file
    $fh=fopen('/home/admin/1.txt',"a+");
    
    // Get the message from stdin 
    $fd    = fopen("php://stdin", "r");  
    $lines = array();
    while ($line=fgets($fd)) {
    $lines[]=$line;
    }
    fclose($fd);
    
    // Write it out
    fwrite($fh,"Content:".json_encode($lines)."\n");
    fclose($fh);
    ?>

that doing just fine, and in 1.txt i see message.

But script

#!/usr/bin/php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Load PHPMailer library
require 'vendor/autoload.php';

// Create PHPMailer object
$mail = new PHPMailer(true);

try {
    // Configure SMTP server settings
    $mail->isSMTP();
    $mail->Host = 'mail.contoso.com';
    $mail->Port = 25;

    // Get message from stdin stream
    $fd = fopen("php://stdin", "r");
    $message = '';
    while ($line = fgets($fd)) {
        $message .= $line;
    }
    fclose($fd);

    // Extract alias from message subject
    $subject = '';
    preg_match('/Subject: (.+)/', $message, $matches);
    if (isset($matches[1])) {
        $subject = $matches[1];
        $alias = 'My Alias'; // Your code to extract alias from message subject
        $mail->Subject = str_replace($subject, $alias, $subject);
    } else {
        throw new Exception('Subject not found in message.');
    }

    // Configure message parameters
    $mail->setFrom('[email protected]', 'Sender Name');
    $mail->addAddress('[email protected]', 'user');
    $mail->Body = $message;

    // Send message
    $mail->send();

    // Write log to /tmp/message.txt file
    $log_message = "Message sent successfully." . PHP_EOL;
    $log_message .= "Subject: " . $mail->Subject . PHP_EOL;
    $log_message .= "From: " . implode(",", $mail->getFromAddresses()) . PHP_EOL;
    $log_message .= "To: " . implode(",", $mail->getToAddresses()) . PHP_EOL;
    file_put_contents('/tmp/message.txt', $log_message, FILE_APPEND | LOCK_EX);
} catch (Exception $e) {
    // Write error to /tmp/message.txt file
    file_put_contents('/tmp/message.txt', 'Error: ' . $e->getMessage() . PHP_EOL, FILE_APPEND | LOCK_EX);
}

Nothing hapens at all. message.txt empty. Yea, this script from Monica. I don't know PHP and how it works.

Postfix log:

postfix/smtpd[75592]: connect from mail.contoso.com[192.168.70.80] 
postfix/smtpd[75592]: 5AA2641: client=mail.contoso.com[192.168.70.80] 
postfix/cleanup[75596]: 5AA2641: message-id=<[email protected]> postfix/qmgr[72497]: 5AA2641: from=<[email protected]>, size=4222, nrcpt=1 (queue active) postfix/smtpd[75592]: disconnect from mail.contoso.com[192.168.70.80] ehlo=2 starttls=1 mail=1 rcpt=1 bdat=1 quit=1 commands=7 postfix/pipe[75597]: 5AA2641: to=<[email protected]>, orig_to=<[email protected]>, relay=etof, delay=0.12, delays=0.04/0.02/0/0.05, dsn=2.0.0, status=sent (delivered via etof service (use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception;  // Load PHPMailer libr?)) 
postfix/qmgr[72497]: 5AA2641: removed

I just can't seem to get it working. Please, how i can get it work?

Now script working. In stdin script get

Return-Path: <[email protected]>
Received: from contoso.com (mx1.contoso.com [192.168.70.80])
        by srv-postrelaytosms-01.local (Postfix) with ESMTPS id 54C9F647
        for <[email protected]>; Fri, 14 Jul 2023 03:57:15 +0000 (UTC)
From: =?koi8-r?B?68Hb1MHMwdAg7cHL08nNIPPF0sfFxdfJ3g==?=
        <[email protected]>
To: "'[email protected]'" <[email protected]>
Subject: 11
Thread-Topic: 11
Thread-Index: Adm2B0cvUD5zJn/dTEiL5tSoNrKK5A==
Date: Fri, 14 Jul 2023 03:57:18 +0000
Message-ID: <[email protected]>
Accept-Language: ru-RU, en-US
Content-Language: ru-RU
X-MS-Has-Attach:
X-MS-TNEF-Correlator:
x-originating-ip: [192.168.0.230]
Content-Type: text/plain; charset="koi8-r"
Content-Transfer-Encoding: quoted-printable
MIME-Version: 1.0

1111

Resend email have no subject. And i dont get it, how i can parse alias from To:

This work like im expect

#!/usr/bin/php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Load PHPMailer library
require 'vendor/autoload.php';

// Create PHPMailer object
$mail = new PHPMailer(true);

try {
    // Configure SMTP server settings
    $mail->isSMTP();
    $mail->Host = 'mail.contoso.com';
    $mail->Port = 25;

    // Get message from stdin stream
    $fd = fopen("php://stdin", "r");
    $message = '';
    while ($line = fgets($fd)) {
        $message .= $line;
    }
    fclose($fd);

    // Extract sender alias from message subject
    $sender_alias = '';
    $sender_email = $mail->From;
    $sender_name = $mail->FromName;
    preg_match('/for <(.+?)@srv-postrelaytosms-01.local>/', $message, $matches);
    if (isset($matches[1])) {
        $sender_alias = trim($matches[1]);
    }

    // Replace message subject with sender alias
    $subject = '';
    preg_match('/Subject: (.+)/', $message, $matches);
    if (isset($matches[1])) {
        $subject = $matches[1];
        if (!empty($sender_alias)) {
            $mail->Subject = str_replace($subject, $sender_alias, $subject);
        }
    } else {
        throw new Exception('Subject not found in message.');
    }

    // Configure message parameters
    $mail->setFrom('[email protected]', 'relay');
    $mail->addAddress('[email protected]', 'user');
    $mail->Body = $subject;

    // Send message
    $mail->send();

    // Write log to /tmp/message.txt file
    $log_message = "Message sent successfully." . PHP_EOL;
    $log_message .= "Subject: " . $mail->Subject . PHP_EOL;
    $log_message .= "From: " . implode(",", [$sender_name, $sender_email]) . PHP_EOL;
    $log_message .= "To: " . implode(",", $mail->getToAddresses()) . PHP_EOL;
    file_put_contents('/tmp/message.txt', $log_message, FILE_APPEND | LOCK_EX);
} catch (Exception $e) {
    // Write error to /tmp/message.txt file
    file_put_contents('/tmp/message.txt', 'Error: ' . $e->getMessage() . PHP_EOL, FILE_APPEND | LOCK_EX);
}
?>
0

There are 0 best solutions below