如何在我的代码中发送多个电子邮件? [英] how to send mutiple emails in my code?

查看:37
本文介绍了如何在我的代码中发送多个电子邮件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将电子邮件发送给多个收件人,但是我的代码出现错误.我需要将电子邮件发送给多个收件人.

I need to send the email to the multiple recipients but I am getting error in my code. I need to send the email to multiple recipients.

<?php    
require 'phpmailer/PHPMailerAutoload.php';

if(isset($_POST['send']))
{
  $email = $_POST['email'];                    
  $password = $_POST['password'];
  $to_id = $_POST['toid'];
  $message = $_POST['message'];
  $subject = $_POST['subject'];

  $mail = new PHPMailer;

  $mail->isSMTP();

  $mail->Host = 'mail.domain.com';

  $mail->Port = 587;

  $mail->SMTPSecure = 'tls';

  $mail->SMTPAuth = true;

  $mail->Username = $email;

  $mail->Password = $password;

  $mail->setFrom('info@domain.com', 'name');

  $mail->addReplyTo('info@domain.com', 'name');

  $mail->addAddress($to_id);

  $mail->Subject = $subject;

  $mail->msgHTML($message);

  if(!$mail->send()) {
    $error = "Mailer Error: " . $mail->ErrorInfo;
  ?>
    <script>alert('<?php echo $error ?>');</script>
  <?php
  } 
  else {
    echo "Message Sent Successfully";
  }
}
?>

推荐答案

尝试以下代码.

require 'PHPMailer/PHPMailerAutoload.php';
function SendPHPMail($to, $from, $subject, $htmlContent, $attachments = array())
    {
        $mail = new PHPMailer;
        $mail->isSMTP();
        $mail->Host = 'smtp.gmail.com';
        $mail->SMTPAuth = true;
        $mail->Username = 'emailAddress@gmail.com'; 
        $mail->Password = 'password';
        $mail->SMTPSecure = 'tls';
        $mail->Port = 25;
        $mail->SMTPOptions = array(
                'ssl' => array(
                        'verify_peer' => false,
                        'verify_peer_name' => true,
                        'allow_self_signed' => true
                )
        );

        $mail->From = 'emailAddress@gmail.com'; //sender emailAddress
        $mail->FromName = 'name'; //sender name

        //Here $to has multiple emailAddress
        //$to = array('address1@domain.com','address2@domain.com','address3@domain.com');
        if(!empty($to)){
            foreach($to as $emailAddress){
                $mail->addAddress($emailAddress);
            }
        } else{
            throw new \Exception('No emails found!');
        }

        if(!empty($attachments)){
            foreach($attachments as $attachment){
                $mail->addAttachment($attachment);
            }
        } 

        //$mail->addCC();

        $mail->WordWrap = 50;
        $mail->isHTML(true);

        $mail->Subject = $subject;
        $mail->Body    = $htmlContent;

         if(!$mail->send()) {
            throw new \Exception($mail->ErrorInfo);
        } 
    }

这篇关于如何在我的代码中发送多个电子邮件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆