Send e-mail by attaching a local file

0

I need a PHP script that, when executed, automatically sends a certain file attachment location in an email.

This is not a web form filled out by the user. It is automatic sending when the script runs whenever someone opens the page.

    
asked by anonymous 02.04.2015 / 15:53

2 answers

5

You can make use of the class PHPMailer to facilitate sending the email.

Here is an example of how you can achieve what you want:

// Incluir a classe no teu ficheiro
require_once '/caminho/para/class.phpmailer.php';

// Instanciar a classe para envio de email
$mail = new PHPMailer(true);

// Vamos tentar realizar o envio
try {

    // Remetente
    $mail->AddReplyTo('[email protected]', 'Meu Nome');
    $mail->SetFrom('[email protected]', 'Meu Nome');

    // Destinatário
    $mail->AddAddress('[email protected]', 'Destinatário');

    // Assunto
    $mail->Subject = 'Segue ficheiro anexo com XPTO';

    // Mensagem para clientes de email sem suporte a HTML
    $mail->AltBody = 'Em anexo o ficheiro com XPTO.';

    // Mensagem para clientes de email com suporte a HTML
    $mail->MsgHTML('<p>Em anexo o ficheiro com XPTO.</p>');

    // Adicionar anexo
    $caminho = '/caminho/completo/para/ficheiro/';
    $ficheiro = 'anexo.pdf';

    $mail->AddAttachment($caminho.$ficheiro);

    // Enviar email
    $mail->Send();

    echo "Mensagem enviada!";
}
catch (phpmailerException $e) {
    // Mensagens de erro do PHPMailer
    echo $e->errorMessage();
}
catch (Exception $e) {
    // Outras mensagens de erro
    echo $e->getMessage();
}

The code above can be saved inside a PHP file, for example enviaMail.php , which file whenever it is called or included in another one will trigger the sending of the email.

    
02.04.2015 / 16:10
0

PHP has a native function called mail, it is found here in the link manual, a small detail is that both to use the PHPMailer class (already quoted above) as the native mail function you need to have an email server on your machine, otherwise you will get an error in response.

    
08.04.2015 / 23:34