开发者

Sending Email with content from PHP/Mysql

开发者 https://www.devze.com 2023-01-13 10:43 出处:网络
I want to send emails where the data is from a php/mySQL query. I know that html will render in the email but i don\'t think the php codes will.

I want to send emails where the data is from a php/mySQL query.

I know that html will render in the email but i don't think the php codes will.

So is there any way where i can send emails with content queried from a mySQL DB ?

开发者_StackOverflow中文版

I already search here, there is one topic that covers it but the person who advised suggested a pdf export or to use a 3rd party tool which in my case are not applicable.

Thank you for the help guys :)


Use PHPMailer to generate the email on the server. It makes it very easy to generate multi-part messages (plaintext + html, with attachments and embedded/inline images). Basically:

// set up PHPMailer
$mail = new PHPMailer();
$mail->SetFrom('you@yourserver.com');
$mail->AddReplyTo('you@somewhereelse.com');
$mail->Subject('Your profile');
$mail->IsHTML(TRUE);

// do your database query
$con = connect_to_database();
$stmt = run_database_query($con, "SELECT ... FROM ...");

$data = fetch_from_database($stmt);


// set the email address
$mail->AddAddress($data['email'], $data['fullname']);


// html content for smart email clients
$html = <<<EOL
<h1>Welcome</h1>

<p>Your username is {$data['username']}.</p>
EOL;

// plain text alternate content
$text = <<<EOL
Welcome

Your username is {$data['username']}.
EOL;

// add the content to the mail
$mail->MsgHTML($html);
// add alternate content 
$mail->AltBody($text);


// send the mail
if ($mail->Send()) {
   // mail sent correctly
} else {
   die("Uhoh, could not send to {$mail['email']}:" . $mail->ErrorInfo);
}


To avoid spam issues you can wrap the PHPMailer in a class and instantiate that at every e-mail address read from the database table.

For each email address you can create a new instance and do kind of a ->setMailAddr($mail,$fullName) and after send the e-mail destroy this instance.

The ideal is to place a new instance at every POST. In this case, you can put a FORM into the page.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号