<?php

require_once("phpmailer/class.phpmailer.php");

function enviaEmailSMTP($recipients, $subject, $body, $from='sistemas.gfa.0@gmail.com', $fromname='sistemas.gfa.0@gmail.com', $cc=null, $bcc=null, $anexos=null, $conta='sistema') {
    switch ($conta) {
        case 'recuperacaoSenha':
            $user = 'sistemas.gfa.recuperacaosenha@gmail.com';
            $userpassword = 'efobcakxclxszdqv';//'efobcakxclxszdqv'(senha de app) '53nh4@enviagmail'(senha da conta)
            break;
        default :
            $user = 'sistemas.gfa.0@gmail.com';
            $userpassword = 'egscqkztpquchhzu';//'egscqkztpquchhzu'(senha de app) '53nh4@enviagmail'(senha da conta)
    }

    $mail = new PHPMailer();

    $mail->IsSMTP();  // Ativar SMTP
//    $mail->SMTPDebug = 1;  // Debugar: 1 = erros e mensagens, 2 = mensagens apenas
    $mail->IsHTML(true); // corpo HTML
    $mail->Mailer = 'smtp'; // Protocolo
    $mail->SMTPAuth = true;  // Autenticação ativada
    $mail->SMTPSecure = 'ssl'; // SSL REQUERIDO pelo GMail
//    $mail->Host = 'ssl://smtp.gmail.com'; // SMTP utilizado
    $mail->Host = 'smtp.gmail.com'; // SMTP utilizado
//    $mail->Port = 587;    // A porta tsl 587 deverá estar aberta em seu servidor
    $mail->Port = 465;    // A porta ssl 465 deverá estar aberta em seu servidor
    $mail->Username = $user;
    $mail->Password = $userpassword;

    $mail->From = $from;
    $mail->FromName = (!empty($fromname)) ? $fromname : $from;

    $mail->AddReplyTo($from);

    $mail->CharSet = 'utf-8';

    $mail->Subject = $subject;

    $address = explode(',', $recipients);
    foreach ($address as $recipient) {
        $recipient = strtolower(str_replace(' ', '', $recipient));
        $mail->AddAddress($recipient);
    }

    if (!empty($cc)) {
        $addresscc = explode(',', $cc);
        foreach ($addresscc as $recipient) {
            $recipient = strtolower(str_replace(' ', '', $recipient));
            $mail->AddCC($recipient);
        }
    }

    if (!empty($bcc)) {
        $addressbcc = explode(',', $bcc);
        foreach ($addressbcc as $recipient) {
            $recipient = strtolower(str_replace(' ', '', $recipient));
            $mail->AddBCC($recipient);
        }
    }

    $mail->MsgHTML($body);

    if (!empty($anexos)) {
        foreach ($anexos as $anexo) {
            if (!empty($anexo[tmp_name]))
                $mail->AddAttachment($anexo[tmp_name], $anexo[name]);
        }
    }

    $enviou = $mail->Send(); // Envia

    $mail->ClearAllRecipients(); // Limpa os recipents
    $mail->ClearAttachments(); // Limpa os anexos

    if (!$enviou) {
        echo $mail->ErrorInfo;
        return false;
    } else {
        return true;
    }
}