How to send email automatically?

Asked

Viewed 7,710 times

5

How to send emails automatically using PHP?

I have a form that receives several dates and when it was 10 days before the deadline, send a message to several people with the warning.

I’ve been told to use the Cron job. But this serves only to make the routine run.

What I need is help with the code because I’ve been trying to put the code in the 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);
}

?>
  • What would be watering?

  • Improve your code, it’s all "piled up" and so make it difficult for those who want to help you.

  • @user3253195, avoid using <? (instead use <?php , @ (can use for example isset()) and the functions mysql_ have already been depreciated. not to have future problems.

  • @user3253195, Will php run on a linux or windows server? For Windows servers you have to add the data of an smtp server to the PHP settings, in the case if a linux server PHP uses sendmail to send. Your problem may be happening at this point.

  • It will be for use on a Windows server. Ah Maybe I’m missing that part anyway

7 answers

2


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

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

For sendmail, which is faster, just access the site below and download the zip.

http://glob.com.au/sendmail/

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

;sendmail=

Peel it off so it stays the way down:

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

It always works for me.

  • Sorry? Let me get this straight. I have to unzip the zip folder and put it where? I’m using Wamp to test. At the end I have : sendmail($item, $mail_from, $mail_to, $Subject, $message); I have to change to sendmail_path? or add?

  • Create the following folders recursively. C:/usr/lib/sendmail/ .

2

Use this my function, 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;
}
  • I will use only php . more or less as you have there and with the changes that has given @lost

  • this code is all php

2

Use Datediff mysql to perform the compute between.

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

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

your code should stay that way:

$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, to improve the readability and performance of your consultation.

  • Exactly, I want to use this shape. Then in the middle and put? $To = $Subject = $Message = $Headers = "

  • @user3253195, in place of //enviar emails you put the other rules, remember that subject and message can be the same content so you can stay out of the while

2

I was able to get Php to send an email. I ended up using Phpmailer. I leave the code for those who need 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;
 }
 ?>

1

There’s a weirder way for you to use that routine, I’d put it on login master, which can be ID = 1, do a search if it is the condition you want it performs its function if it does not continue. gave to understand?

  • 1

    If I understand what you’re saying, that’s not the question. Running the task is not the problem, the problem seems to be that the email sending code does not work.

1

What’s the problem you’re getting ?

Displays some error on the screen?

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

The starting point for sending email is check if your server accepts mail

If your server does not accept mail, you should send it using SMTP. Start with the basics by firing email with the function mail or a SMTP shipping class

  • Welcome. In fact there is no information in the question and you still can not ask for more details in comment until you have more reputation. When you can, edit the answer to keep only what answers the question.

  • Do I have to install something because of SMTP? I’m sorry for the questions but this is the first time to venture into these fields

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 value of content is in seconds):

<meta http-equiv="refresh" content="5">
  • What code below?

  • I added there..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.