PHP将图像嵌入HTML电子邮件中

问题描述

我可以使用此脚本成功发送通用电子邮件。但是,当我添加代码以在邮件头顶部的徽标中显示徽标时,所有内容都会爆炸。我收到一个HTTP错误。我认为这与引号有关。

$to = $email;
    $subject = "My Website Email Confirmation";

    $message = "
    <html>
    <head>
        <title>My Website Email Confirmation</title>
    </head>
    <body>
        <header>
            <img src="https://www.mywebsite.com/images/logo_transparent_background.png" height="70px">
        </header>
        <br>
        <br>
        <p>Welcome to My Website. We are excited to be working with you. Please click here to confirm your email address.
        <br>
        <br>Best regards,<br>Your Team
        </p>
    </body>
    </html>
    ";

    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    $headers .= 'From: <nor[email protected]>' . "\r\n";

    mail($to,$subject,$message,$headers);

解决方法

我最终使用了PHPMailer。尽管起初有些混乱,但最终效果很好。我不是每天都用这些东西,所以我需要花一点时间将它包裹起来。我跟随几个YouTube视频到达那里。它需要在我的Web服务器上安装:

https://www.youtube.com/watch?v=EM630O5W-_I

然后澄清了一些编码问题,尤其是图像相关的编码问题:

https://www.youtube.com/watch?v=ZamAho2_vcM

https://www.youtube.com/watch?v=CRwW3l6dhSE

https://www.ustrem.org/en/articles/send-mail-using-phpmailer-en/

在(1)将其安装在Web服务器上并(2)使用上面的资源以更好地理解代码之后,此代码对我有用:

require "phpmailertesting/PHPMailer/PHPMailerAutoload.php";

function smtpmailer($to,$from,$from_name,$subject,$body)
{
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = true; 
    $mail->SMTPSecure = 'ssl'; 
$mail->Host = 'mail.mywebsite.com';
$mail->Port = 465;  
$mail->Username = 'autoreply@ mywebsite.com';
$mail->Password = '##############';

$mail->AddEmbeddedImage('images/logo_transparent_background.png','logoimg');

$mail->IsHTML(true);
$mail->From="autoreply@ mywebsite.com";
$mail->FromName=$from_name;
$mail->Sender=$from;
$mail->AddReplyTo($from,$from_name);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AddAddress($to);
    if(!$mail->Send())
    {
                $error ="Please try Later,Error Occured while Processing...";
                return $error; 
            }
            else 
            {
                $error = "Thanks You !! Your email is sent.";  
                return $error;
            }
    }
    
$to   = $email;
$from = 'autoreply@ mywebsite.com';
$name = 'My Website';
$subj = 'My Website Email Confirmation';
$msg = '<h1><img src=cid:logoimg height="70px"></h1><br>'
.'<p>Greetings,we are looking forward to working with you!"</p><br>'
.'<p>Please <a href="https://www. mywebsite.com/validateemail.php">click here</a> to validate your email address.</p><br>'
.'<p>Once that is complete,we are ready to start your customized plan!</p><br>'
.'<p>Or,you can <a href="https://www. mywebsite.com/signin.php">sign-in</a> here once confirmed.<br>'
.'<p>Best regards,</p><br>'
    .'<p>Your Team</p><br>';

$error=smtpmailer($to,$name,$subj,$msg);