To send emails use the function mail()
php here.
To send more elaborately there is the Phpmailer library available here
In both cases you will need to study how to use both.
As the form of triggering your thinking is on the table and should not, the action of sending email should happen whenever the page is executed, or you will need to assemble a script running from time to time evaluating the situation and sending emails.
It is very common to have routines in the system, this can be done through some kind of task scheduler, although it is the most correct I realize that is not what you are looking for at the moment.
1st Option
Place the email trigger on the page loading itself, using an email sending function:
if ($data_atual_1mes > $validade_motorista) {
if(sendMail('[email protected]', 'Validade Expirada', 'Conteúdo do e-mail', null) {
//e-mail enviado
}
else {
//e-mail não enviado
}
echo '<span style="color: red;">Expirado!</span>';
}
2nd option via AJAX
This does not override the first option that can continue to be executed but further below it:
if($_POST['ajax']) {
$response = "";
if ($data_atual_1mes > $validade_motorista) {
if(sendMail('[email protected]', 'Validade Expirada', 'Conteúdo do e-mail', null) {
//e-mail enviado
$response = '<span style="color: red;">Expirado! Email OK</span>';
}
else {
$response = '<span style="color: red;">Expirado! Email NOK</span>';
}
}
else {
$response = '<span style="color: lime;">Válido</span>';
}
//mata a execução disponibilizando a resposta
die($response);
}
Javascript (jQuery Ajax):
var expiraMotorista = function () {
$.ajax({
url: 'arquivo.php', //arquivo a ser executado
type: 'POST', //ou GET
data: {ajax: true} //parametros a serem enviados no POST/GET
})
.done(function(response) {
//concluído sem erro
//aqui seria possível atualizar a tabela com o response, usando um id <span id='situacao'>
$("#situacao").html(response);
console.log("sucesso");
})
.fail(function() {
//falhou
console.log("erro");
})
.always(function() {
//executa sempre que concluído
console.log("expiraMotorista() executada");
});
}
var interval = window.setInterval('expiraMotorista()', 10000); //10 segundos
expiraMotorista();
Follows a simple function I use to send emails using Phpmailer:
function sendMail($dests = null, $assunto = null, $body = null, $anexos = null) {
global $mail_error;
if($dests && $assunto) {
//adiciona as bibliotecas
require 'PHPMailer6/src/PHPMailer.php';
require 'PHPMailer6/src/Exception.php';
require 'PHPMailer6/src/SMTP.php';
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->SMTPDebug = SMTP::DEBUG_OFF;
//enviar utilizando o gmail
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->SMTPAuth = true;
//dados da conta, se for gmail precisa habilitar o acesso a conta
$mail->Username = "[email protected]";
$mail->Password = "senha";
//e-mail e nome que aparecerão na caixa dod destinatario
$mail->setFrom('[email protected]', 'Remetente');
$mail->CharSet = 'UTF-8';
//adicionando os destinarios, espera-se um array
if(is_array($dests) && count($dests) > 0) {
foreach($dests as $d) {
$mail->addAddress(trim($d));
}
$dests = implode(",",$dests); //para reportar os e-mails no erro
}
else {
if($dests) {
$mail->addAddress(trim($dests));
}
}
//adicionando os anexos, espera-se um array
if(is_array($anexos)) {
foreach ($anexos as $key => $anexo) {
$mail->addStringAttachment($anexo['arquivo'], $anexo['nome_anexo'].'.pdf');
}
}
else {
if($anexos) {
$mail->addAttachment(trim($anexos));
}
}
//assunto do e-mail
$mail->Subject = $assunto;
//este e-mail pode conter conteúdo html
$mail->isHTML(true);
//corpo do e-mail
$mail->Body = $body;
//se enviado
if ($mail->send()) {
return true;
}
else {
//setar o erro na variavel global e pegar após a execução da função
$mail_error = "Houve erro no envio do e-mail para ($dests): {$mail->ErrorInfo}";
return false;
}
}
else {
$mail_error "Destinatário ou assunto não informado";
return false;
}
}
Perfect, thank you very much for the answer. I have a question regarding your first recommendation, to put a function in the page load, would not be triggered e-mail every time the page was loaded? Or you would also need to create a function that checks which id’s have already been sent and which ones have not...
– Jonas Felipe
I haven’t talked about it myself, but it’s fair that idependente of the choice there should be a control of who has already had the shipment performed, it’s usually a daughter table of the driver, or a general control table of e-mails, when sending the email records it and also saves if there was success or error in sending if there is a record of sending email that has succeeded after.
– Cleverson