【问题标题】:Enter new line for mail body PHP为邮件正文 PHP 输入新行
【发布时间】:2019-12-27 05:53:25
【问题描述】:

我对邮件正文的“输入”有疑问。我使用 textarea 作为表单中的输入,然后将其提交以通过 gmail 发送。问题是,正文总是有“\r\n”而不是“输入”。我尝试了许多建议,例如 nl2br、trim 等,但仍然无法正常工作。

这是我的代码:

这是表格

<?php
session_start();
$user_id = $_SESSION['id'];
include 'config.php';
$tabel = mysqli_query($mysqli, "SELECT * FROM tabel WHERE id=".$_GET['id']."");
$row = mysqli_fetch_array($tabel);
$name = $row['name'];
$getname = $mysqli->query("SELECT * FROM list_email WHERE name = '$name'");
$row2 = $getname->fetch_array();
$id = $_GET['id'];
?>

<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="js/bootstrap.min.js"></script>

<body style='background-color:lightblue'>
<br>
<div class="container h-100">
    <div class="justify-content-center align-items-center">
        <h1 class="text-center">Kirim Email</h1>
        <br><br>
        <form class="col-12" action="kirim_email.php?id=<?php echo $id; ?>" method="post">

            <div class="form-group form-row">
                <div class="col-md-3"></div>
                <div class="col-md-7">
                    <a href="vendor/phpmailer/phpmailer/get_oauth_token.php" type="button" class="btn btn-success">Tambah/Cek Token (Login Gmail)</a>
                </div>
            </div> 
            <br>
            <div class="form-group form-row">
                <div class="col-md-1"></div>
                <label for="to" class="col-md-2 col-form-label">To:</label>
                <div class="col-md-8">
                    <input type="text" class="form-control" id="to" name="kepada" placeholder="To" value="<?php echo $row2['email1']; ?>">
                </div>
            </div>         
            <div class="form-group form-row">
                <div class="col-md-1"></div>
                <label for="cc" class="col-md-2 col-form-label">CC:</label>
                <div class="col-md-8">
                    <input type="text" class="form-control" id="cc" name="cc" placeholder="CC" value="<?php echo $row2['email2'].",email@gmail.com"; ?>">
                </div>
            </div>
            <div class="form-group form-row">
                <div class="col-md-1"></div>
                <label for="subject" class="col-md-2 col-form-label">Subject:</label>
                <div class="col-md-8">
                        <input type="text" class="form-control" id="subject" name="subject" placeholder="Subject" value="<?php echo "Subject" ?>">
                </div>
            </div>
            <br>
            <div class="form-group form-row">
                <div class="col-md-1"></div>
                <label for="message" class="col-md-2 col-form-label">Message:</label>
                <div class="col-md-8">
                    <textarea class="form-control" id="message" name="message" placeholder="Message" rows="5"><?php echo "Dear my Friend,\n\nHere is the file you want\n\nRegards,\nMe" ?></textarea>
                </div>
            </div>
            <br>
            <div class="form-group form-row">
                <div class="col-md-3"></div>
                <div class="col-md-1,5">
                    <button type="submit" class="btn btn-primary">Confirm</button>
                </div>
            </div>
        </form>
    </div>
</div>

发送邮件代码:

<?php
require('mc_table.php');
include 'config.php';
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
// Load Composer's autoloader
//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\OAuth;

// Alias the League Google OAuth2 provider class
use League\OAuth2\Client\Provider\Google;

//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
date_default_timezone_set('Etc/UTC');

//Load dependencies from composer
//If this causes an error, run 'composer install'
require 'vendor/autoload.php';

$tabel = mysqli_query($mysqli,"SELECT * FROM tabel WHERE id=".$_GET['id']."");
$row=mysqli_fetch_array($tabel);
$pdf=new PDF_MC_Table('P','mm','A4');
$pdf->AddPage();
$pdf->SetAutoPageBreak(true);
$cellWidth = 138;
$cellHeight = 10;

$pdf->SetFont('Arial', 'BI', 12);
$pdf->Cell(190, 7, 'FORM', 0, 1, 'C');


$pdf->SetFont('Arial', 'B', 12);
if($row['tipe']=='tipe1'){
    $pdf->Cell(190, 5, 'New', 0, 1, 'C');
}
else{
    $pdf->Cell(190, 5, 'Old', 0, 1, 'C');
}
$pdf->Cell(10, 2, '', 0, 1);

$pdf->SetFont('Arial', 'B', 10);
$pdf->Cell(0, 10, 'To : ' . $row['kepada'], 0, 0, 'L');
$pdf->Cell(0, 10, '', 0, 1);
$oldY = $pdf->getY();

$pdf->SetFont('Arial','',10);
$pdf->SetWidths(array(50,2,138));
$pdf->Cell(50, 7, ' Name', 0, 0, 'L');
$pdf->Cell(0, 7, ': '. $row['name'], 0, 0, 'L');
$pdf->Cell(0, 7, '', 0, 1);

//Address
$alamat = strlen($row['address']);
if($alamat>84){
    $pdf->Row(array(" Address",":",$row['address']));
}
else{
    $pdf->Cell(50, 7, ' Address', 0, 0, 'L');
    $pdf->Cell(0, 7, ': '.$row['address'], 0, 0, 'L');
    $pdf->Cell(0, 7, '', 0, 1);
}

//Border
$newY = $pdf->getY();
$multiCellHeight = $newY-$oldY;
$pdf->Rect(10,39,190,$multiCellHeight);

if($row['upload']!=""){
    $pdf->AddPage();
    $query = $mysqli->query("SELECT upload FROM tabel WHERE id = '$_GET[id]'");
    //$pdf ->WriteHTML('<style>
    //      img {
    //      width: 100%;
    //      height: auto;
    //      }
    //    </style>');
    if($query->num_rows > 0) {
        while ($row = $query->fetch_assoc()) {
            $exploded = explode(",", $row["upload"]);
            $line = true;
            $number = 0;
            $numbers = 0;
            $maxatt = 0;
            foreach($exploded as $item){
                $maxatt++;
            }
            foreach ($exploded as $item){            
                list($width,$height) = getimagesize('uploads/tabel/' . $_GET['id'] . '_attachment/' . $item);
                if($width >= 1920 || $height >= 1080){
                    $imgWidth = $width/20; // set whatever width you want for the image to be rendered
                    $imgHeight = $height/20;
                }
                else{
                    $imgWidth = $width/10; // set whatever width you want for the image to be rendered
                    $imgHeight = $height/10;
                }
                $imgX = (210-$imgWidth)/2;
                $imgY = $pdf->getY(); // use the current Y position

                $pdf->Image('uploads/tabel/' . $_GET['id'] . '_attachment/'.$item,$imgX,$imgY,$imgWidth,$imgHeight);
                /*if($pdf->getY() > 300){
                    $pdf->AddPage();
                }*/
                $pdf->Ln(80);
                $number++;
                $numbers++;

                if($numbers<$maxatt){
                    if($number==3){
                        $pdf->AddPage();
                        $number=0;
                    }
                }
            }
        }
    }
}

$email = file_get_contents('email.txt');
$kepada = mysqli_real_escape_string($mysqli, $_POST['kepada']);
$cc = mysqli_real_escape_string($mysqli, $_POST['cc']);
$subject = mysqli_real_escape_string($mysqli, $_POST['subject']);
$message = mysqli_real_escape_string($mysqli, $_POST['message']);
$attachment = $pdf->Output('S','');
$tabel2 = mysqli_query($mysqli,"SELECT * FROM tabel WHERE id=".$_GET['id']."");
$row3=mysqli_fetch_array($tabel2);
$name = $row3['name'];
$namafile = $name.".pdf";

sendEmail($attachment,$email,$kepada,$cc,$subject,$message,$namafile);

function sendEmail($pdf,$email,$kepada,$cc,$subject,$message,$namafile){
    //Create a new PHPMailer instance
    $mail = new PHPMailer;

    //Tell PHPMailer to use SMTP
    $mail->isSMTP();

    //Enable SMTP debugging
    // SMTP::DEBUG_OFF = off (for production use)
    // SMTP::DEBUG_CLIENT = client messages
    // SMTP::DEBUG_SERVER = client and server messages
    $mail->SMTPDebug = SMTP::DEBUG_SERVER;

    //Set the hostname of the mail server
    $mail->Host = 'smtp.gmail.com';

    //Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
    $mail->Port = 587;

    //Set the encryption mechanism to use - STARTTLS or SMTPS
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;

    //Whether to use SMTP authentication
    $mail->SMTPAuth = true;

    //Set AuthType to use XOAUTH2
    $mail->AuthType = 'XOAUTH2';

    //Fill in authentication details here
    //Either the gmail account owner, or the user that gave consent
    $clientId = "clientId";
    $clientSecret = "clientsecret";

    //Obtained by configuring and running get_oauth_token.php
    //after setting up an app in Google Developer Console.
    $refreshToken = file_get_contents('token.txt');

    //Create a new OAuth2 provider instance
    $provider = new Google(
        [
            'clientId' => $clientId,
            'clientSecret' => $clientSecret,
        ]
    );
    //Pass the OAuth provider instance to PHPMailer
    $mail->setOAuth(
        new OAuth(
            [
                'provider' => $provider,
                'clientId' => $clientId,
                'clientSecret' => $clientSecret,
                'refreshToken' => $refreshToken,
                'userName' => $email,
            ]
        )
    );

    //Set who the message is to be sent from
    //For gmail, this generally needs to be the same as the user you logged in as
    $mail->setFrom($email);

    //Set who the message is to be sent to
    $mail->addAddress($kepada);

    $exploded = explode(",", $cc);
    foreach ($exploded as $item) {
        $mail->addCC($item);
    }

    // Attachments
    $mail->addStringAttachment($pdf, $namafile);

    //Set the subject line
    $mail->Subject = $subject;

    //Read an HTML message body from an external file, convert referenced images to embedded,
    //convert HTML into a basic plain-text alternative body
    $mail->CharSet = PHPMailer::CHARSET_UTF8;
    $mail->isHTML(true);

    $mail->Body = echo mysqli_real_escape_string($mysqli, str_replace("\n","<br/>",$message));

    //Attach an image file  

    //send the message, check for errors
    if (!$mail->send()) {
        echo 'Mailer Error: '. $mail->ErrorInfo;
    } else {
        echo 'Message sent!';
    }
}
?>

【问题讨论】:

  • 我通常使用&lt;br/&gt;,我知道这是一个黑客,但它对我来说就像这样echo "Hello World &lt;br/&gt; World Hello";
  • 您是在创建 HTML 电子邮件还是简单的文本电子邮件?
  • 如果您尝试发送 HTML 电子邮件,请检查 w3schools.com/php/func_mail_mail.asp 如果您直接从 textarea 发送数据,也将换行符 \n 替换为
    标签。如果您是文本编辑器,则无需将换行符更改为
  • 对不起,它仍然无法与您合作 isHTML(true)
  • 我正在使用 phpmailer 通过 gmail 发送电子邮件。我使用 google oauth 登录,关于邮件,它来自我的表单

标签: php phpmailer newline


【解决方案1】:

试试类似的东西

echo mysqli_real_escape_string($mysqli, str_replace("\n","<br/>",$_POST['message']));

您只能在发送电子邮件时替换 \n,而不是在 textarea 中。

在 PHPMailer 中,$mail-&gt;isHTML(true); // 将电子邮件格式设置为 HTML

查看更多信息: Sending emails with PHPMailer

【讨论】:

  • 嗯,如何放置 echo 语句?
  • @AdityaVictory Write $message = mysqli_real_escape_string($mysqli, str_replace("\n","
    ",$_POST['message']));
【解决方案2】:

您可能以 HTML 格式发送电子邮件,而您的文本区域包含普通文本。您应该用&lt;br/&gt; 标记替换换行符(\r\n\n)。你可以使用:

$emailBody  = str_replace(["\r\n", "\n"] , "<br/>", $emailBody);
//OR
$emailBody = nl2br($emailBody);

对于 nl2br,请参阅documentation

【讨论】:

  • 为什么在 str_replace 中使用方括号?
  • 我可以简单地做str_replace("\n" , "&lt;br/&gt;", $emailBody),但我想用
    替换 \r \n 和 \n 会更清楚。不是吗?
  • 我已经按照类似问题的建议尝试了 replace 和 nl2br ,但这些对我的情况不起作用。我不知道,如果我把它放在变量中,也许“\n”只是读为纯文本而不是“输入”?
  • 将 \n 替换为
    结果相同,除了
    在文本区域和邮件正文中都可见
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-27
  • 1970-01-01
  • 1970-01-01
  • 2013-11-28
  • 1970-01-01
  • 2014-05-11
相关资源
最近更新 更多