Zeigt Inline-Bildanhänge mit wp_mail an

Lesezeit: 5 Minuten

Eeks Benutzeravatar
Eek

Ich habe ein Problem.

Ich möchte ein Bild an eine E-Mail anhängen und es auch inline mit einigen anderen von PHP generierten Inhalten anzeigen. Das Problem ist, dass ich nicht die geringste Ahnung habe, wie man ein Dateianhangsarray, das von wp_mail zum Anhängen verwendet wird, inline verwendet.

Meine Lösung bestand darin, die Bilder in base64 zu codieren und sie wie folgt in den HTML-Code einzufügen:

<img alt="The Alt" src="data:image/png;base64,*etc*etc*etc" />

Das Problem ist jedoch, dass Gmail / Outlook die src-Daten aus dem Bild entfernt. So landet es als

<img alt="The Alt" />

Irgendwelche Hinweise, was zu ändern ist (Header, um mit base64 zu arbeiten) oder wie man Anhänge verwendet, um sie inline einzubetten?

Benutzeravatar von Constantin
Konstantin

wp_mail nutzt die PHPMailer Klasse. Diese Klasse verfügt über alle Funktionen, die für Inline-Anhänge erforderlich sind. Um das phpmailer-Objekt zu ändern, bevor wp_mail() die E-Mail sendet, können Sie den Filter verwenden phpmailer_init.

$body = '
Hello John,
checkout my new cool picture.
<img src="https://stackoverflow.com/questions/15646187/cid:my-cool-picture-uid" width="300" height="400">

Thanks, hope you like it ;)';

Das war ein Beispiel dafür, wie Sie das Bild in Ihren E-Mail-Text einfügen.

$file="/path/to/file.jpg"; //phpmailer will load this file
$uid = 'my-cool-picture-uid'; //will map it to this UID
$name="file.jpg"; //this will be the file name for the attachment

global $phpmailer;
add_action( 'phpmailer_init', function(&$phpmailer)use($file,$uid,$name){
    $phpmailer->SMTPKeepAlive = true;
    $phpmailer->AddEmbeddedImage($file, $uid, $name);
});

//now just call wp_mail()
wp_mail('[email protected]','Hi John',$body);

Das ist alles.

  • Denken Sie an das Semikolon am Ende der Zeile nach „file.jpg“.

    – janlindso

    25. Oktober 2014 um 22:26 Uhr

Tomys Benutzeravatar
Zu meinem

Wenn Sie einen unerwarteten T_FUNCTION-Fehler erhalten, liegt dies an der PHP-Version < 5.3. Erstellen Sie in diesem Fall eine Funktion, um dies auf traditionellere Weise zu tun:

function attachInlineImage() {  
  global $phpmailer;  
  $file="/path/to/file.jpg"; //phpmailer will load this file  
  $uid = 'my-cool-picture-uid'; //will map it to this UID  
  $name="file.jpg"; //this will be the file name for the attachment  
  if (is_file($file)) {  
    $phpmailer->AddEmbeddedImage($file, $uid, $name);  
  }  
}  

add_action('phpmailer_init','attachInlineImage');  

Ich brauchte das etwas besser, weil ich mehrere Mails in einem Schritt versende und nicht alle Mails die gleichen eingebetteten Bilder haben sollten. Also verwende ich diese Lösung von Constantin, aber mit meinen Modifikationen 🙂

wp_mail('[email protected]', 'First mail without attachments', 'Test 1');

$phpmailerInitAction = function(&$phpmailer) {
    $phpmailer->AddEmbeddedImage(__DIR__ . '/img/header.jpg', 'header');
    $phpmailer->AddEmbeddedImage(__DIR__ . '/img/footer.png', 'footer');
};
add_action('phpmailer_init', $phpmailerInitAction);
wp_mail('[email protected]', 'Mail with embedded images', 'Example <img src="https://stackoverflow.com/questions/15646187/cid:header" /><br /><img src="cid:footer" />', [
    'Content-Type: text/html; charset=UTF-8'
], [
    __DIR__ . '/files/terms.pdf'
]);
remove_action('phpmailer_init', $phpmailerInitAction);

wp_mail('[email protected]', 'Second mail without attachments', 'Test 2');

Der Erste wp_mail wird ohne Anhänge sein. Der Zweite wp_mail enthält eingebettete Bilder. Der dritte wp_mail wird ohne Anhänge sein.

Im Moment funktioniert es gut 😎

Ich habe diese Klasse erstellt, um das Hinzufügen eines Bildes zum E-Mail-Text zu verwalten und danach aufzuräumen.

Auch wenn Sie definieren SENDGRID_PASSWORDwird Sendgrid anstelle Ihres Servers zum Senden von E-Mails verwendet

Dieser Artikel ist eine Schritt-für-Schritt-Anleitung zum Einbetten von Bildern in den E-Mail-Text mit WordPress

https://codewriteups.com/embed-images-in-email-body-using-wp_mail-and-phpmailer

<?php

/*
 * Send HTML Emails with inline images
 */
class Custom_Mailer
{
    public $email_attachments = [];

    public function send($to, $subject, $body, $headers, $attachments)
    {
        /* Used by "phpmailer_init" hook to add attachments directly to PHPMailer  */
        $this->email_attachments = $attachments;

        /* Setup Before send email */
        add_action('phpmailer_init', [$this, 'add_attachments_to_php_mailer']);
        add_filter('wp_mail_content_type', [$this, 'set_content_type']);
        add_filter('wp_mail_from', [$this, 'set_wp_mail_from']);
        add_filter('wp_mail_from_name', [$this, 'wp_mail_from_name']);
        
        /* Send Email */
        $is_sent = wp_mail($to, $subject, $body, $headers);
        
        /* Cleanup after send email */
        $this->email_attachments = [];
        remove_action('phpmailer_init', [$this, 'add_attachments_to_php_mailer']);
        remove_filter('wp_mail_content_type', [$this, 'set_content_type']);
        remove_filter('wp_mail_from', [$this, 'set_wp_mail_from']);
        remove_filter('wp_mail_from_name', [$this, 'wp_mail_from_name']);

        return $is_sent;
    }

    public function add_attachments_to_php_mailer(&$phpmailer)
    {
        $phpmailer->SMTPKeepAlive=true;
        
        /* Sendgrid */
        if (defined('SENDGRID_PASSWORD')) {
            $phpmailer->IsSMTP();
            $phpmailer->Host="smtp.sendgrid.net";
            $phpmailer->Port = 587;
            $phpmailer->SMTPAuth = true;
            $phpmailer->SMTPSecure="tls";
            $phpmailer->Username="apikey";
            $phpmailer->Password = SENDGRID_PASSWORD;   /* api key from sendgrid */
        }

        /* Add attachments to mail */
        foreach ($this->email_attachments as $attachment) {
            if (file_exists($attachment['path'])) {
                $phpmailer->AddEmbeddedImage($attachment['path'], $attachment['cid']);
            }
        }
    }

    public function set_content_type()
    {
        return "text/html";
    }
    
    public function set_wp_mail_from($email)
    {
        //Make sure the email is from the same domain
        //as your website to avoid being marked as spam.
        return strip_tags(get_option('admin_email'));
    }

    public function wp_mail_from_name($name)
    {
        return get_bloginfo('name');
    }
}

Verwendungszweck:

/* Set mail parameters */
$to = '[email protected]';
$subject="Inline Img";
$body = '<h1>Image:</h1> <img src="cid:my_img_cid"/>';
$headers = "";
$my_attachments = [
    [
        "cid" => "my_img_cid", /* used in email body */
        "path" => plugin_dir_path(__FILE__) . '/my_img.png',
    ],
];

$custom_mailer = new Custom_Mailer();
$custom_mailer->send($to, $subject, $body, $headers, $my_attachments);

AddEmbeddedImage akzeptiert nur zwei Parameter, achten Sie also darauf, den $name-Parameter nicht wie im Beispiel einzuschließen.

  • Es wäre hilfreich, auch einen Link zu den Dokumenten bereitzustellen, um Ihre Behauptung zu untermauern und für weitere Recherchen.

    – sjaustirni

    27. Februar 2018 um 13:17 Uhr

Benutzeravatar von Dharman
Dharman

Fügen Sie den folgenden Code in die functions.php ein, um Ihr Bild in alle E-Mails aufzunehmen (wie ein Signaturlogo).

function attachInlineLogo() {
    global $phpmailer;
    if (!( $phpmailer instanceof PHPMailer )) {
        require_once ABSPATH . WPINC . '/class-phpmailer.php';
        require_once ABSPATH . WPINC . '/class-smtp.php';
        $phpmailer = new PHPMailer(true);
    }
    $strFilePath="ABSOLUTE LOGO PATH";
    $strFileUID  = 'UNIQUE-UID'; //UID TO USE IN HTML TEMPLATE
    $strFileName="LOGO NAME";
    if (is_file($strFilePath)) {
        $phpmailer->SMTPKeepAlive = true;
        $phpmailer->AddEmbeddedImage($strFilePath, $strFileUID, $strFileName);
    }
}

add_action('phpmailer_init', 'attachInlineLogo');

In Ihrem HTML-Code

<img src="https://stackoverflow.com/questions/15646187/cid:UNIQUE-UID" />

  • Es wäre hilfreich, auch einen Link zu den Dokumenten bereitzustellen, um Ihre Behauptung zu untermauern und für weitere Recherchen.

    – sjaustirni

    27. Februar 2018 um 13:17 Uhr

1392530cookie-checkZeigt Inline-Bildanhänge mit wp_mail an

This website is using cookies to improve the user-friendliness. You agree by using the website further.

Privacy policy