How to send email through an HTML page?

Asked

Viewed 906 times

-1

How to send an email to a recipient established on a page HTML?

  • 3

    I think this has been answered before. Either way you need to give more details than you have already done. What I can say is that essentially you can’t send directly from the page in a standard and reliable way.

2 answers

3


1st OPTION:

1º I used Mandriljs which is a service that sends me 12 Thousand emails for free to you (this is not spam). works as a field medium to not need a server.

Access link (you need to create an account): Mandrills

2º Create a common form and (put as method POST just not to fill the URL but nothing will be sent to a server) in the send button do it this way:

<button onClick="sendMail();return false;">Enviar</button>

3rd Create a Javascript with a function of the same name as the button that will recover the fields filled by the form user:

function sendMail(){
    var nome = document.getElementById("nome").value;
    var email = document.getElementById("email").value;
    var assunto = document.getElementById("assunto").value;
    var desc = document.getElementById("desc").value;
    var body = '<strong>Nome: </strong>'+nome+'<br />'+
               '<strong>Email: </strong>'+email+'<br />'+
               '<strong>Assunto: </strong>'+assunto+'<br />'+
               '<strong>Descição: </strong>'+desc;

    $.ajax({
        type:"POST",
        url:"https://mandrillapp.com/api/1.0/messages/send.json",
        data:{
                'key':'sua chave aqui',
                'message':{
                    'from_email':'email que irá enviar',
                    'to':[
                        {
                            'email':'email remetente',
                            'name':'Seu Nome (ou nick)',
                            'type':'to'
                        }
                    ],
                    'subject':'Assunto',
                    'html':body
                }
            }
    });
}

OBS1: You do not need to enter your email passwords anywhere, you should only register with MandrilJS (without entering password of your emails) and generating a key, key that will be inserted in the json in the specific location (it is generated in the settings).

OBS2: It is necessary jQuery.

OBS3: You can insert CSS into tags

OBS4: Both Emails have to be validated by the Recipient for obvious missteps he will receive the emails, Remente why Mandrijs sends weekly email sent and read statistics.

2nd OPTION:

I use the Phpmailer class for this purpose (it is necessary at least one GMAIL for this since we will use your SMTP server) I am putting some methods that make use of this class (all documented).

Link to Phpmailer download: http://phpmailer.worxware.com/

    /**
    *String que armazena o email de onde partirá os emails (remetente).
    *@var string
    */
    const GUSER = 'email';

    /**
    *String que armazena a senha do email de onde partirá os emails (remetente).
    *@var string
    */
    const GPWD = 'senha';

    /**
    *String que armazena o email para qual as mensagens serão enviadas (destinatário).
    *@var string
    */
    const GSEND = 'teste';


   static function contactUsEmail(){

        $emailRemetente = $_POST['email'];
        $name = $_POST['name'];
        $subject = $_POST['subject'];
        $mensagem = $_POST["message"];
        $corpoMensagem = '<b>CONCTACT US EMAIL</b>'.'<br /><b>Email Remetente: </b>'.$emailRemetente.
        '<br /><b>Nome:</b>'.$name.'<br /><b>Assunto:</b>'.$subject.'<br /><b>Mensagem:</b>'.$mensagem;

        $sendResult = SendEmail::smtpMailer(SendEmail::GSEND, SendEmail::GUSER, $name, $subject, $corpoMensagem);

        if($sendResult === true){
             echo 'Mensagem Enviada com Sucesso';
        }else{
            echo $sendResult;
        }
    }

    function smtpMailer($destinatario, $remetente, $nomeRemetente, $assunto, $corpo){

        /*
        *Objeto que realizará a composição do email com os dados passados como parametros, 
        *armazenara as configurações do servidor SMTP utilizado e todas as outras configurações 
        *e realizará o envio do email.
        *@var PHPMailer object
        */
        $mail = new PHPMailer();

        /**
        *Define o charset do email a ser enviado.
        */
        $mail->CharSet = 'UTF-8';

        /**
        *Ativa SMTP para uso.
        */
        $mail->IsSMTP();

        /**
        *Não exibirá erros e mensagens, outras configurações possiveis: 
        *Debugar: 1 = erros e mensagens, 2 = mensagens apenas.
        */
        $mail->SMTPDebug = 0;

        /**
        *Ativa a autenticação.
        */
        $mail->SMTPAuth = true;

        /**
        *Protocolo utilizado, o gmail (servidor utilizado) requere o uso de tls.
        */
        $mail->SMTPSecure = 'tls';

        /**
        *SMTP utilizado
        */
        $mail->Host = 'smtp.gmail.com';

        /**
        *Porta utilizado para envio de mensagens (ela deverá estar aberta em seu servidor).
        */
        $mail->Port = 587;

        /**
        *Login do usuário utilizado para envio do email (no caso usuário comum do gmail).
        */
        $mail->Username = SendEmail::GUSER;

        /**
        *Senha do login de usuário utilizado para envio do email.
        */
        $mail->Password = SendEmail::GPWD;

        /**
        *Identificação do remetente do email (usuário de email utilizado para envio do 
        *email pelo sistema (logo de propriedade do sistema) e o nome do usuário remetente 
        *(informado na hora da criação do email)) do email.
        */
        $mail->SetFrom($remetente, $nomeRemetente);

        /**
        *Assunto do email.
        */
        $mail->Subject = $assunto;

        /**
        *Corpo do email.
        */
        $mail->Body = $corpo;

        /**
        *Email destinatário do email (de propriedade do sistema).
        */
        $mail->AddAddress($destinatario);

        /**
        *Seta o email como HTML (por padrão ele é text/plain).
        */
        $mail->IsHTML(true);

        $sendResult = $mail->Send();

        if(!$sendResult){
            return "<b>Informações do erro:</b> " . $mail->ErrorInfo;
        }else{
            return true;
        }
    }
  • The Mandrill is very good, but I’ve always used it by the server. No problem exposing the API key in the client?

  • @bfavaretto Look I asked myself this question but in the documentation it says that there are no problems, and to login to the account it is necessary the username and password the key is not used any time.

  • But whoever gets this key could be emailing your name, using your Mandrill quota. I think this JS API was created for use on Node, not browsers.

  • If I do not miss the memory there is how to organize campaigns with each key you generate (you can generate several keys).

  • Yes, but my point is, if you can do something with just the key, whoever knows the key can do the same. (I’m not questioning your answer, even it gives other options and I voted +1 on it; I’m just trying to clarify this issue of Mandrill).

  • I will check if it is possible to restrict the origin of the emails by the Mandrill server

Show 2 more comments

0

Use the element a informing on the attribute href email details such as subject (subject), recipient (mailto:) and body of the message (body). Blank spaces separating each word in the subject and text of the message should be reported as the combination of characters %20.

Example:

<a href="mailto:[email protected]?subject=Assunto%20da%20mensagem&body=Conteúdo%20da%20mensagem">Enviar email</a>
  • 3

    This does not send an email, it simply opens the client configured by the browser with the fields filled, it does not seem to be what the AP wants.

Browser other questions tagged

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