How to send email automatically?

5

How to automatically send emails using PHP?

I have a form that receives several dates and when there is 10 days to finish the deadline, a message is sent to several people with the warning.

I've been told to use the Cron job . But this is just to make the routine run.

I need help in the code because I've been experimenting with code in Windows Task Manager and nothing.

<?php 
include(conectar.php);
$conn = @mysql_connect($local_serve, $usuario_serve, $senha_serve, $banco_de_dados)
    or die ("O servidor não responde!");

// conecta-se ao banco de dados
$db = @mysql_select_db($banco_de_dados,$conn)
    or die ("Não foi possivel ligar-se a Base de Dados!");

$validade = ("SELECT Nome, AlvaraValidade, AcidenteValidade, SeguroValidade, FinancasValidade, SocialValidade, RemuneracaoValidade, InstaladorValidade, MontadorValidade, MedicaValidade, ProjectistaValidade, GasValidade, RedesValidade, SoldadorValidade, MecanicoValidade, ClasSoldadorValidade, MaquinaValidade1, MaquinaValidade2, MaquinaValidade3, MaquinaTopoValidade FROM tb_eqipamentos, tb_detalhe_trabalhador, tb_trabalhador");
$now = new DateTime();
$diff = $now ($validade);

if ($diff <= 10){
    $mail_to = "[email protected]";
    while ($row = mysql_fetch_array($query)){
    echo $row['name']." - ".$row['email']."\n";
    $mail_to = $row['email'].", ";
}
if (!empty($mail_to)){
    sendEmail($mail_to);
}

?>
    
asked by anonymous 30.01.2014 / 16:48

7 answers

2

It really seems that your problem is in the configuration of the mail server.

When I need to send email from windows, I use sendmail for windows or set up a smtp connection.

For sendmail, which is faster, just go to the website below and download the zip.

link

To work in PHP, I unpack it in the C: \ usr \ lib \ sendmail folder. Locate the following line in your local php.ini:

;sendmail=

Uncomment it to make it look like this:

sendmail_path = "C:/usr/lib/sendmail/sendmail.exe -t -i"

It always works for me.

    
01.02.2014 / 05:06
2

Use datediff from mysql to perform the calculates between the dates.

$validade = ("SELECT Nome, AlvaraValidade, AcidenteValidade, 
SeguroValidade, FinancasValidade, SocialValidade, RemuneracaoValidade,
....//sql longo);

$validade is only a string and not a query, you need to use mysql_query() to excute it. If the result is more than one line utlilze a while together with mysql_fetch_assoc()

Your code should look like this:

$sql = "SELECT <campos> FROM tb_eqipamentos, tb_detalhe_trabalhador, tb_trabalhador  
WHERE datediff(now(), data) = 10 "

$validade = mysql_query($sql);

while($item = mysql_fetch_assoc($validade)){
    //enviar emails
    sendMail($item['email'];
}

I recommend taking a look at inner join , for improve the readability and performace of your query.

    
30.01.2014 / 17:28
2

I managed to get Php to send email. I ended up using PhpMailer. I leave the code to whoever needs it. Thank you all

$PHPMailer = new PHPMailer();

// define que será usado SMTP
$PHPMailer->IsSMTP();

// envia email HTML
$PHPMailer->isHTML( true );

// codificação UTF-8, a codificação mais usada recentemente
$PHPMailer->Charset = 'UTF-8';

// Configurações do SMTP
$PHPMailer->SMTPAuth = True;
$PHPMailer->SMTPSecure = '....';
$PHPMailer->Host = '....';
$PHPMailer->Port = '25';
$PHPMailer->Username = '....';
$PHPMailer->Password = '....';

// E-Mail do remetente (deve ser o mesmo de quem fez a autenticação
// nesse caso [email protected])
$PHPMailer->From = '....';

// Nome do rementente
$PHPMailer->FromName = '....';

// assunto da mensagem
$PHPMailer->Subject = '.....';

// corpo da mensagem
$PHPMailer->Body = '<p>Mensagem em HTML</p>';

// corpo da mensagem em modo texto
$PHPMailer->AltBody = 'Mensagem em texto';

// adiciona destinatário (pode ser chamado inúmeras vezes)
$PHPMailer->AddAddress( '......' );

// adiciona um anexo
$PHPMailer->AddAttachment( '' );

// verifica se enviou corretamente
if ( $PHPMailer->Send() )
{
echo "Enviado com sucesso";
}
else
 {
echo 'Erro do PHPMailer: ' . $PHPMailer->ErrorInfo;
 }
 ?>
    
05.02.2014 / 15:20
1

Use this function of mine, just call it with the 3 variables with your values.

function EnviarMail($destinatario, $assunto, $mensagem)
{
    $de = "[email protected]";
    $headers = "From: O_TEU_NOME <".$de.">\n";
    $headers .= "Content-Type: Text/HTML; charset=UTF-8\n";

    // formatação da mensagem em HTML
    $mensagem = '<html>
    <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head>
    <body>
    ' . $mensagem . '
    </body>
    </html>';

    $ok = mail($destinatario,$assunto,$mensagem,$headers);

    return $ok;
}
    
30.01.2014 / 17:21
1

What is the problem you are getting?

Display some screen error?

From what I understand in your code, you check if the validity is less than 10 and does not execute anything else.

The starting point for sending e-mail is checking if your server accepts mail

If your server does not accept mail, you must send it using SMTP. Start with the basic triggering email with the mail function or a SMTP send class

    
30.01.2014 / 17:20
1

It has a strange more functional way of using this routine, I would put in the login master , which can be the ID = 1, do a search if it is the condition that you want it executes your function, if it does not continue. Can you understand?

    
01.02.2014 / 03:06
1

One option is to leave this page open in a browser giving refresh from time to time ...

For this you can use the code below (the content value is in seconds):

<meta http-equiv="refresh" content="5">
    
30.01.2014 / 17:21