Email Attachment

Discussions related to customizing hooks. Hooks are documented at http://bigprof.com/appgini/help/advanced-topics/hooks/
Post Reply
User avatar
aarlauskas
Veteran Member
Posts: 127
Joined: 2019-04-28 18:03
Location: Medway, UK

Email Attachment

Post by aarlauskas » 2021-01-03 21:01

Hi, I have a form which includes image field. There is also an email script in hook that sends an email with some of the field data when this form is submitted. If user attach the image in the form, is there a way to include the image/attachment in the email?
Thanks.

fciprian
Veteran Member
Posts: 53
Joined: 2020-04-20 10:51

Re: Email Attachment

Post by fciprian » 2021-02-13 23:38

Any news about this topic?

User avatar
onoehring
AppGini Super Hero
AppGini Super Hero
Posts: 1212
Joined: 2019-05-21 22:42
Location: Germany
Contact:

Re: Email Attachment

Post by onoehring » 2021-02-14 08:50

Hi,

I would suggest looking into AG genereated code. In incFunctions.php you find the sendmail function which essentially uses phpmailer ( https://github.com/PHPMailer/PHPMailer ). Probably it's the easiest to check the sendmail code, copy and adjust it into your own function and add the option to give attachments on the way.
Please see the docs in the mentioned URL.

Olaf

User avatar
rngoda
Veteran Member
Posts: 157
Joined: 2020-02-05 16:00
Location: KENYA
Contact:

Re: Email Attachment

Post by rngoda » 2025-02-17 19:48

Adding Attachments to Emails Using AppGini's Built-in Mail Function

This guide provides step-by-step instructions to add file attachments when sending emails using AppGini's built-in mail function.



Step 1: Locate the Hooks Folder and Edit __global.php
  1. Open your AppGini project folder (e.g., C:\xampp8.2\htdocs\your_project_name).
    Navigate to the hooks folder.
  2. Find and open __global.php using a text editor (e.g., Notepad++, VSCode).


Step 2: Modify the sendmail_handler Function

Code: Select all

function sendmail_handler(&$pm)
{
$tag = $pm->tag;

if (is_array($tag) && !empty($tag['attachment_path'])) {
    $attachment_paths = explode(',', $tag['attachment_path']);
    foreach ($attachment_paths as $path) {
        $pm->AddAttachment(trim($path));
    }
}

}
Explanation:

Reads attachment_path from the email tag.

Splits multiple paths using commas.

Adds each attachment via AddAttachment().



Step 3: Example Usage for Sending Emails with Attachments

Code: Select all

$mail = [
"to" => "[email protected]",
"name" => "Sender Name",
"message" => "Hello, this is a test email",
"subject" => "Test Email",
"tag" => ["attachment_path" => "C:\xampp8.2\htdocs\apolloerp/alte_uploads/file.png"]
];
$send = sendmail($mail);
To Add Multiple Attachments:

Code: Select all

"tag" => ["attachment_path" => "path/to/file1.png,path/to/file2.pdf"]
Note: Paths should be relative to your project directory.


Step 4: Verify the Setup
  1. Save changes to __global.php.
    Send a test email.
  2. Confirm the email includes the correct attachments.


✅ Final Notes:

The sendmail_handler hook integrates seamlessly with AppGini.

Add multiple files using a comma-separated list.

Ensure file paths are correct and accessible.

This guide helps you easily implement attachments in emails sent from your AppGini project.
I'm a software engineer specializing in web database application development for complex scalable web apps.
Buy Admiro Dashboard Theme For Appgini HERE
Buy AdminLTE Plugin For Appgini: HERE
Buy Cloud Storage Plugin For Appgini HERE

Checkout AdminLTE Plugin For Appgini Tutorials On Youtube

For support Email: [email protected] Whatsappp: Me Here


User avatar
crnjak
Veteran Member
Posts: 43
Joined: 2021-12-29 20:25

Re: Email Attachment

Post by crnjak » 2025-02-23 21:57

Hi i have a request to send bulk email from adress in table who name is "kontakti".
How to create a button to do a selection of records from the table, so that it collects the selected emails from the records and to type out a message?

User avatar
crnjak
Veteran Member
Posts: 43
Joined: 2021-12-29 20:25

Re: Email Attachment

Post by crnjak » 2025-02-27 08:34

i do it and its work so i decide to share my expirience:

first edit tablename.php with email field.

Code: Select all

	function kontakti_batch_actions(&$args) {

		return [
			[
				'title' => 'POŠALJI EMAIL',
				'function' => 'bulk_slanje_email',
				'icon' => 'envelope'
			]
		];
	}
them create in hooks tablename-tv.js with this code:

Code: Select all

function bulk_slanje_email(table_name, ids) {

    var url = 'send_bulk_email.php?table=' + table_name;
    for(var i = 0; i < ids.length; i++){
        url = url + '&'
            + encodeURI('ids[]') + '='
            + encodeURIComponent(ids[i]);
    }

    window.open(url);
}
code for page send_bulk_email.php:

Code: Select all

<?php
// 1. Uključivanje AppGini biblioteka i PHPMailer klasa
include(__DIR__ . "/lib.php");

require_once __DIR__ . '/PHPMailer/src/Exception.php';
require_once __DIR__ . '/PHPMailer/src/PHPMailer.php';
require_once __DIR__ . '/PHPMailer/src/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Slanje Email Poruke</title>
    <!-- Uključujemo Bootstrap CSS (CDN putanja) -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    <!-- (Opciono) Bootstrap ikone -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css">
</head>
<body>

<div class="container my-5">
    <?php
    // Ako je kliknuto "Pošalji" -> obrada POST zahteva
    if($_SERVER['REQUEST_METHOD'] === 'POST') {
        // ~~~~~~~~~~~~~~~~~~~~~
        // 2. LOGIKA ZA SLANJE 
        // ~~~~~~~~~~~~~~~~~~~~~

        // 2.1 Prikupi vrednosti iz POST-a
        $table   = $_POST['table']   ?? '';
        $ids     = $_POST['ids']     ?? [];
        $poruka  = $_POST['poruka']  ?? '';
        $subject = $_POST['subject'] ?? '';

        // 2.2 Napravi listu ID-jeva za SELECT
        $cs_ids = '';
        foreach($ids as $id) {
            $cs_ids .= "'" . makeSafe($id) . "',";
        }
        $cs_ids = rtrim($cs_ids, ',');

        // 2.3 Uzmi email adrese iz baze
        $eo = ['silentErrors' => true];
        $query = "SELECT email FROM kontakti WHERE id IN ({$cs_ids})";
        $res   = sql($query, $eo);

        // 2.4 Postavljanje PHPMailer-a za slanje preko SMTP-a
        $mail = new PHPMailer(true);

        try {
            // SMTP setovanja ( prilagodi svojim potrebama )
            $mail->isSMTP();
            $mail->Host       = 'mail.test.com';
            $mail->SMTPAuth   = true;
            $mail->Username   = 'YOUR_EMAIL_USERNAME';
            $mail->Password   = 'YOUR_EMAIL_PASSWORD';
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            $mail->Port       = 465; //port is 465 for SSL

            // Od koga se šalje
            $mail->setFrom('[email protected]', 'TEST BULK');

            // 2.5 Dodaj primaoce (BCC ako ne želiš da se vide međusobno)
            while($row = db_fetch_assoc($res)) {
                $primac = $row['email'];
                if(!$primac) continue;
                $mail->addBCC($primac);
            }

            // 2.5a Ako je korisnik dodao fajl (attachment), dodajemo ga
            if(
                isset($_FILES['attachment']) &&
                $_FILES['attachment']['error'] === UPLOAD_ERR_OK &&
                !empty($_FILES['attachment']['tmp_name'])
            ) {
                // Drugi parametar je naziv fajla, kako će se videti u email-u
                $mail->addAttachment(
                    $_FILES['attachment']['tmp_name'],
                    $_FILES['attachment']['name']
                );
            }

            // 2.6 Podesi sadržaj
            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body    = nl2br($poruka);

            // 2.7 Slanje
            $mail->send();

            // Obaveštenje o uspešnom slanju (Bootstrap alert)
            echo '<div class="alert alert-success" role="alert">
                    <strong>Uspeh!</strong> Email je uspešno poslat svim izabranim adresama.
                  </div>';
        } catch (Exception $e) {
            // Ako se desi greška pri slanju
            echo '<div class="alert alert-danger" role="alert">
                    <strong>Greška!</strong> Slanje emaila nije uspelo. 
                    Detalji: ' . htmlspecialchars($mail->ErrorInfo) . '
                  </div>';
        }
    } else {
        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        // 3. PRIKAZ STRANICE (GET metod)
        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        // 3.1 Uzmemo table i ids koje smo prosledili
        $table = $_REQUEST['table'] ?? '';
        $ids   = $_REQUEST['ids']   ?? [];

        // 3.2 Sastavimo listu ID-jeva
        $cs_ids = '';
        foreach($ids as $id) {
            $cs_ids .= "'" . makeSafe($id) . "',";
        }
        $cs_ids = rtrim($cs_ids, ',');

        // 3.3 Izvučemo email adrese iz baze (samo radi prikaza)
        $eo = ['silentErrors' => true];
        $query = "SELECT email FROM kontakti WHERE id IN ({$cs_ids})";
        $res   = sql($query, $eo);

        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        // DODATA LOGIKA ZA PRIKAZ PRVIH 5
        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        $emails = [];
        while($row = db_fetch_assoc($res)) {
            $emails[] = $row['email'];
        }

        $totalEmails   = count($emails);               
        $displayEmails = array_slice($emails, 0, 5);   // prikazujemo do 5
        ?>
        <!-- Naslov strane -->
        <h2 class="mb-4">Slanje Email Poruke</h2>

        <!-- Kartica sa spiskom email adresa i formom -->
        <div class="card shadow-sm">
            <div class="card-body">
                <h5 class="card-title">Biće poslato sledećim email adresama:</h5>

                <!-- Prikazujemo samo prvih 5 emailova -->
                <ul class="list-group list-group-flush mb-4">
                    <?php foreach($displayEmails as $mailItem) { ?>
                        <li class="list-group-item">
                            <i class="bi bi-envelope-fill me-2 text-primary"></i>
                            <?php echo htmlspecialchars($mailItem); ?>
                        </li>
                    <?php } ?>
                    
                    <?php if($totalEmails > 5) { 
                        $remaining = $totalEmails - 5; 
                        ?>
                        <li class="list-group-item bg-light text-secondary">
                            ... i još <?php echo $remaining; ?> adresa
                        </li>
                    <?php } ?>
                </ul>

                <!-- Forma koja poziva ovaj isti fajl preko POST metoda -->
                <!-- Enctype je bitan za slanje fajlova -->
                <form method="post" enctype="multipart/form-data">
                    <!-- Prenosimo parametre table i ids preko hidden polja -->
                    <input type="hidden" name="table" value="<?php echo htmlspecialchars($table); ?>" />
                    <?php foreach($ids as $id) { ?>
                        <input type="hidden" name="ids[]" value="<?php echo htmlspecialchars($id); ?>" />
                    <?php } ?>

                    <div class="mb-3">
                        <label for="subject" class="form-label">Naslov:</label>
                        <input type="text" id="subject" name="subject" class="form-control" required>
                    </div>

                    <div class="mb-3">
                        <label for="poruka" class="form-label">Poruka:</label>
                        <textarea id="poruka" name="poruka" class="form-control" rows="5" required></textarea>
                    </div>

                    <!-- NOVO: polje za prilog/attachment -->
                    <div class="mb-3">
                        <label for="attachment" class="form-label">Dodaj prilog:</label>
                        <input type="file" id="attachment" name="attachment" class="form-control">
                    </div>

                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-send-fill"></i> Pošalji
                    </button>
                </form>
            </div>
        </div>
        <?php
    }
    ?>
</div>

<!-- Uključi Bootstrap JS (CDN) ako želiš interaktivne komponente -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

after that copy PHPMailer on root of your project:

Code: Select all

your-project/
  ├─ PHPMailer/
  │   └─ src/
  │       ├─ Exception.php
  │       ├─ PHPMailer.php
  │       └─ SMTP.php
  ├─ send_bulk_email.php
Labels and buttons you can edit for your language.


xbox2007
Veteran Member
Posts: 152
Joined: 2016-12-16 16:49

Re: Email Attachment

Post by xbox2007 » 2025-03-21 20:17

thanks a lot rngoda

Post Reply