Email Sending via Proxy - JavaMail

0

This is my code: (UPDATED 2) I UPDATED THE CONFIG OF MY ACCOUNT. Allow access by external apps and it worked !!!

PS: but I had to make the suggested changes too. So I marked the answer below as correct!

MAIN CALLING METHOD:

package TudoQueTesta;

import TudoQueTesta.Nova;

public class Testes {

    public static void main(String[] args) {

        Nova sm = new Nova("smtp.gmail.com","465"); 

        sm.sendMail("[email protected]","[email protected]","Teste ","teste text/plain");

    }

}
    package TudoQueTesta;

import java.util.Properties;  
import javax.mail.Message;  
import javax.mail.Session;  
import javax.mail.Transport;  
import javax.mail.internet.InternetAddress;  
import javax.mail.internet.MimeMessage;   
import javax.mail.Authenticator;  
import javax.mail.PasswordAuthentication;   

public class Nova {  

    private String mailSMTPServer;  
    private String mailSMTPServerPort;  

    /* 
     * quando instanciar um Objeto ja sera atribuido o servidor SMTP do GMAIL  
     * e a porta usada por ele 
     */  
    Nova() { //Para o GMAIL   
        mailSMTPServer = "smtp.gmail.com";  
        mailSMTPServerPort = "**465**";  
    }  
    /* 
     * caso queira mudar o servidor e a porta, so enviar para o contrutor 
     * os valor como string 
     */  
    Nova(String mailSMTPServer, String mailSMTPServerPort) { //Para outro Servidor  
        this.mailSMTPServer = mailSMTPServer;  
        this.mailSMTPServerPort = mailSMTPServerPort;  
    }  

    public void sendMail(String from, String to, String subject, String message) {  

        Properties props = new Properties();  

                // quem estiver utilizando um SERVIDOR PROXY descomente essa parte e atribua as propriedades do SERVIDOR PROXY utilizado  

                //props.setProperty("proxySet","true"); 
                //props.setProperty("socksProxyHost","proxysp.sp.t-systems.com.br"); // IP do Servidor Proxy 
               // props.setProperty("socksProxyPort","8002");  // Porta do servidor Proxy 


        props.put("mail.transport.protocol", "smtp"); //define protocolo de envio como SMTP  
        props.put("mail.smtp.starttls.enable","true");   
        props.put("mail.smtp.host", mailSMTPServer); //server SMTP do GMAIL  
        props.put("mail.smtp.auth", "true"); //ativa autenticacao  
        props.put("mail.smtp.user", "[email protected]"); //usuario ou seja, a conta que esta enviando o email (tem que ser do GMAIL)  
        props.put("mail.debug", "true");  
        props.put("mail.smtp.port", mailSMTPServerPort); //porta  
        props.put("mail.smtp.socketFactory.port", mailSMTPServerPort); //mesma porta para o socket  
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");  
        props.put("mail.smtp.socketFactory.fallback", "false");  

        //Cria um autenticador que sera usado a seguir  
        SimpleAuth auth = null;  
        auth = new SimpleAuth ("[email protected]","********");  

        //Session - objeto que ira realizar a conexão com o servidor  
        /*Como há necessidade de autenticação é criada uma autenticacao que 
         * é responsavel por solicitar e retornar o usuário e senha para  
         * autenticação */  
        Session session = Session.getDefaultInstance(props, auth);  
        session.setDebug(true); //Habilita o LOG das ações executadas durante o envio do email  

        //Objeto que contém a mensagem  
        Message msg = new MimeMessage(session);  

        try {  
            //Setando o destinatário  
            msg.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));  
            //Setando a origem do email  
            msg.setFrom(new InternetAddress("[email protected]"));  
            //Setando o assunto  
            msg.setSubject("Teste");  
            //Setando o conteúdo/corpo do email  
            msg.setContent(**message,"text/plain"**);  

        } catch (Exception e) {  
            System.out.println(">> Erro: Completar Mensagem");  
            e.printStackTrace();  
        }  

        //Objeto encarregado de enviar os dados para o email  
        Transport tr;  
        try {  
            tr = session.getTransport("**smtps**"); //define smtp para transporte  
            /* 
             *  1 - define o servidor smtp 
             *  2 - seu nome de usuario do gmail 
             *  3 - sua senha do gmail 
             */  
            tr.connect(mailSMTPServer, "[email protected]", "*******");  
            msg.saveChanges(); // don't forget this  
            //envio da mensagem  
            tr.sendMessage(msg, msg.getAllRecipients());  
            tr.close();  
        } catch (Exception e) {  
            // TODO Auto-generated catch block  
            System.out.println(">> Erro: Envio Mensagem");  
            e.printStackTrace();  
        }  

    }  
}  

//clase que retorna uma autenticacao para ser enviada e verificada pelo servidor smtp  
class SimpleAuth extends Authenticator {  
    public String username = null;  
    public String password = null;  


    public SimpleAuth(String user, String pwd) {  
        username = user;  
        password = pwd;  
    }  

    protected PasswordAuthentication getPasswordAuthentication() {  
        return new PasswordAuthentication ("benkommers","*******");  
    }  
}  

And here's the situation:

I'm creating an application that all my colleagues and my boss will use. My boss will be the admin with default admin password. However, in order for my colleagues to sign up, I am creating the option to register in the login screen, where the user will enter his corporate email and should thus, clicking on "register" receive an email generated by the application, where the user receives a random password so that he can login for the first time in the application and enter the rest of the information.

I also inserted the company proxy and port, but I still can not connect. I've tried gmail before, but it was not possible.

This is the error:

    DEBUG: JavaMail version 1.5.3
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle]}
DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]}
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: setDebug: JavaMail version 1.5.3
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth false
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 465, isSSL true
220 mx.google.com ESMTP 188sm8807798qhh.48 - gsmtp
DEBUG SMTP: connected to host "smtp.gmail.com", port: 465

EHLO CTS08285355.dc.com.br
250-mx.google.com at your service, [189.34.1.196]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN"
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
DEBUG SMTP: Attempt to authenticate using mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM 
DEBUG SMTP: AUTH LOGIN command trace suppressed
DEBUG SMTP: AUTH LOGIN failed
DEBUG SMTP: useEhlo true, useAuth false
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 465, isSSL true
220 mx.google.com ESMTP f90sm8827513qkf.14 - gsmtp
DEBUG SMTP: connected to host "smtp.gmail.com", port: 465

EHLO CTS08285355.dc.com.br
250-mx.google.com at your service, [189.34.1.196]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN"
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
DEBUG SMTP: Attempt to authenticate using mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM 
DEBUG SMTP: AUTH LOGIN command trace suppressed
DEBUG SMTP: AUTH LOGIN failed
>> Erro: Envio Mensagem
javax.mail.AuthenticationFailedException: 534-5.7.14 <https://accounts.google.com/ContinueSignIn?sarp=1&scc=1&plt=AKgnsbstf
534-5.7.14 2rw_Dpy_Cety3ozxAAxFUComBCb9LS5T8YZJh6PjEzZmv02OH4U-lJY3jNQAk5LUCrz0SG
534-5.7.14 wXoU777Xd6ArydRllw-FlNYZWb79_B0lgX-h6dH1IbTTorvRYYPZ-jstZ3fW8i-U9d6Q7G
534-5.7.14 rPtWotyslr_fQZZ6-VdbRbih7JhY2W2c64IZylfrGnPCzOovpSNBHk3akUEzse0_edofZA
534-5.7.14 u7m5yP3hofqh7A1zezc4N59Ytmq4> Please log in via your web browser and
534-5.7.14 then try again.
534-5.7.14 Learn more at
534 5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754 f90sm8827513qkf.14 - gsmtp

    at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:892)
    at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:814)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:728)
    at javax.mail.Service.connect(Service.java:386)
    at javax.mail.Service.connect(Service.java:245)
    at TudoQueTesta.Nova.sendMail(Nova.java:94)
    at TudoQueTesta.Testes.main(Testes.java:11)
BUILD SUCCESSFUL (total time: 8 seconds)

Am I doing something wrong?

PS: I use Java SE, Netbeans, I have already loaded the jar files from javamail and jaf to the classpath.

    
asked by anonymous 07.05.2015 / 16:23

1 answer

1

Make the following changes to your code because Gmail is trying to send with SSL .

Change the port to 465 .

Change the code to:

msg.setContent(message,"text/plain"); 
tr = session.getTransport("smtps");
    
09.05.2015 / 15:56