participate


JavaMail - JavaMail send a mail through a Proxy Server..(answer) and with Gmail(SSL)
<<   Back to Forum  |   Give us Feedback
This topic has 19 replies on 2 pages.    1 | 2 | Next »
kanweng
Posts:28
Registered: 4/11/05
JavaMail send a mail through a Proxy Server..(answer) and with Gmail(SSL)   
Apr 10, 2005 12:24 PM

 
hi guys

I'm writing an application working with javamail, and I send the mail throgh a proxy server(CCProxy, you can search Google, find it) .

I have searched google to find a solution for that. eventually, i found a tips from one website.

Assumptions


(Sockets v4, v5)
proxy host : 192.168.155.1
proxy port : 1080



Normally, if you ask question like this. people like to answer you
  Properties props = System.getProperties();
         props.setProperty("proxySet","true");
         props.setProperty("ProxyHost","192.168.155.1");
         props.setProperty("ProxyPort","1080");
 

or set the HTTP proxy host and port
 Properties props = System.getProperties();
         props.setProperty("proxySet","true");
         props.setProperty("http.proxyHost","192.168.155.1");
         props.setProperty("http.proxyPort","808");


But above codes will not working with javamail.

well, what should you do,

here is the solution that you can send mail through a proxy server

   Properties p = System.getProperties();
         p.setProperty("proxySet","true");
         p.setProperty("socksProxyHost","192.168.155.1");
         p.setProperty("socksProxyPort","1080");
  


Send Mail through a proxy server (Gmail)

   import java.security.Security;
   import java.util.Date;
   import java.util.Properties;
   import javax.mail.Authenticator;
   import javax.mail.Message;
   import javax.mail.MessagingException;
   import javax.mail.PasswordAuthentication;
   import javax.mail.Session;
   import javax.mail.Transport;
   import javax.mail.internet.AddressException;
   import javax.mail.internet.InternetAddress;
   import javax.mail.internet.MimeMessage;
 
 
   public class GmailSender {
   
      public static void main(String[] args) throws AddressException, MessagingException {
      
      
         Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
         final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
      // Get a Properties object
         Properties props = System.getProperties();
  	 props.setProperty("proxySet","true");
         props.setProperty("socksProxyHost","192.168.155.1");
         props.setProperty("socksProxyPort","1080");
         props.setProperty("mail.smtp.host", "smtp.gmail.com");
         props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
         props.setProperty("mail.smtp.socketFactory.fallback", "false");
         props.setProperty("mail.smtp.port", "465");
         props.setProperty("mail.smtp.socketFactory.port", "465");
         props.put("mail.smtp.auth", "true");
         props.put("mail.debug", "true");
         props.put("mail.store.protocol", "pop3");
         props.put("mail.transport.protocol", "smtp");
         final String username = "USERNAME";
         final String password = "PASSWORD";
         Session session = Session.getDefaultInstance(props, 
                              new Authenticator(){
                                 protected PasswordAuthentication getPasswordAuthentication() {
                                    return new PasswordAuthentication(username, password);
                                 }});
      
       // -- Create a new message --
         Message msg = new MimeMessage(session);
      
      // -- Set the FROM and TO fields --
         msg.setFrom(new InternetAddress("xxxxxx@gmail.com"));
         msg.setRecipients(Message.RecipientType.TO, 
                          InternetAddress.parse("xxxxxx@yahoo.com",false));
         msg.setSubject("Hello");
         msg.setText("How are you");
         msg.setSentDate(new Date());
         Transport.send(msg);
         System.out.println("Message sent.");
      }
   }


Fetch Mail through a proxy server (Gmail)
   import java.io.UnsupportedEncodingException;
   import java.security.*;
   import java.util.Properties;
   import javax.mail.*;
   import javax.mail.internet.InternetAddress;
   import javax.mail.internet.MimeUtility;
 
   public class GmailFetch {
   
      public static void main(String argv[]) throws Exception {
      
         Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
         final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
      
      // Get a Properties object
         Properties props = System.getProperties();
         props.setProperty("proxySet","true");
         props.setProperty("socksProxyHost","192.168.155.1");
         props.setProperty("socksProxyPort","1080");
      
         props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
         props.setProperty("mail.pop3.socketFactory.fallback", "false");
         props.setProperty("mail.pop3.port", "995");
         props.setProperty("mail.pop3.socketFactory.port", "995");
     
         Session session = Session.getDefaultInstance(props,null);
      
      
         URLName urln = new URLName("pop3","pop.gmail.com",995,null,
                           "USERNAME", "PASSWORD");
         Store store = session.getStore(urln);
         Folder inbox = null;
         try {
            store.connect();
            inbox = store.getFolder("INBOX");
            inbox.open(Folder.READ_ONLY);
            FetchProfile profile = new FetchProfile();
            profile.add(FetchProfile.Item.ENVELOPE);
            Message[] messages = inbox.getMessages();
            inbox.fetch(messages, profile);
            System.out.println("Inbox Number of Message" + messages.length);
            for (int i = 0; i < messages.length; i++) {
            
               String from = decodeText(messages[i].getFrom()[0].toString());
               InternetAddress ia = new InternetAddress(from);System.out.println("FROM:" + ia.getPersonal()+'('+ia.getAddress()+')');
            
               System.out.println("TITLE:" + messages[i].getSubject());
            
               System.out.println("DATE:" + messages[i].getSentDate());
            }
         } 
            finally {
               try {
                  inbox.close(false);
               } 
                  catch (Exception e) {
                  }
               try {
                  store.close();
               } 
                  catch (Exception e) {
                  }
            }
      }
   
      protected static String decodeText(String text)
      throws UnsupportedEncodingException {
         if (text == null)
            return null;
         if (text.startsWith("=?GB") || text.startsWith("=?gb"))
            text = MimeUtility.decodeText(text);
         else
            text = new String(text.getBytes("ISO8859_1"));
         return text;
      }
   
   }


Without SSL connection, Normal SMTP
   import java.util.Properties; 
   import javax.mail.*;
   import javax.mail.internet.*;
   import javax.activation.*;
   import java.io.UnsupportedEncodingException;
   import java.security.*;
   import java.util.Properties;
   import javax.mail.*;
   import javax.mail.internet.InternetAddress;
   import javax.mail.internet.MimeUtility;
   public class AttachExample { 
      public static void main (String args[]) throws Exception 
      { 
         System.getProperties().put("proxySet","true");
         System.getProperties().put("socksProxyPort","1080");
         System.getProperties().put("socksProxyHost","192.168.155.1");
         Properties props = System.getProperties(); 
        
         String from = "xxxxx@spymac.com"; 
         String to = "xxxx@yahoo.com";
         String filename = "AttachExample.java";
      
      
      // Get system properties 
         final String username = "USERNAME";
         final String password = "PASSWORD";
      
         props.put("mail.user", username);
         props.put("mail.host", "mail.spymac.com");
         props.put("mail.debug", "true");
         props.put("mail.store.protocol", "pop3");
         props.put("mail.transport.protocol", "smtp");
      
      
         Session session = Session.getDefaultInstance(props, 
                              new Authenticator(){
                                 protected PasswordAuthentication getPasswordAuthentication() {
                                    return new PasswordAuthentication(username, password);
                                 }});
      
      // Define message 
         Message message = new MimeMessage(session);
         message.setFrom(new InternetAddress(from));
         message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); 
         message.setSubject("Hello JavaMail Attachment"); 
      // Create the message part 
         BodyPart messageBodyPart = new MimeBodyPart(); 
      // Fill the message 
         messageBodyPart.setText("Here's the file"); 
      // Create a Multipart 
         Multipart multipart = new MimeMultipart();
      // Add part one
         multipart.addBodyPart(messageBodyPart); 
      // // Part two is attachment // // Create second body part 
         messageBodyPart = new MimeBodyPart(); 
      // Get the attachment 
         DataSource source = new FileDataSource(filename); 
      // Set the data handler to the attachment 
         messageBodyPart.setDataHandler(new DataHandler(source));
      // Set the filename
         messageBodyPart.setFileName(filename); 
      // Add part two 
         multipart.addBodyPart(messageBodyPart); 
      // Put parts in message
         message.setContent(multipart);
      // Send the message 
         Transport.send(message);
      } 
   }
 
tsp_14
Posts:2
Registered: 8/17/05
Re: JavaMail send a mail through a Proxy Server..(answer) and with Gmail(SSL)   
Aug 17, 2005 12:34 AM (reply 1 of 19)  (In reply to original post )

 
hi,kanweng ,your code has helped me a lot ,but if the proxy server requires username and password ,can you tell me what should I do?
 
tsp_14
Posts:2
Registered: 8/17/05
Re: JavaMail send a mail through a Proxy Server..(answer) and with Gmail(SSL)   
Aug 17, 2005 1:38 AM (reply 2 of 19)  (In reply to original post )

 
when running GmailFetch,I got the message(my jdk version is 1.5.0):
Exception in thread "main" javax.mail.MessagingException: Connect failed;
nested exception is:
java.net.SocketException: Malformed reply from SOCKS server
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:120)
at javax.mail.Service.connect(Service.java:233)
at javax.mail.Service.connect(Service.java:134)
at javax.mail.Service.connect(Service.java:86)
at cn.edu.scu.forcast.test.GmailFetcher.main(GmailFetcher.java:37)
 
n0vembr
Posts:14
Registered: 9/1/05
Re: JavaMail send a mail through a Proxy Server..(answer) and with Gmail(S   
Sep 1, 2005 10:42 PM (reply 3 of 19)  (In reply to original post )

 
you're a life saver...thanks so much for sharing your code.. :) God bless
 
cw99
Posts:3
Registered: 11/29/05
Re: JavaMail send a mail through a Proxy Server..(answer) and with Gmail(S   
Nov 29, 2005 2:33 PM (reply 4 of 19)  (In reply to #3 )

 
hello, i tried the gmailsender piece of code. however i have an error
on this line:
getPasswordAuthentication() {
return new PasswordAuthentication(xxxxx@gmail.com, xxxxx);
}});
for the username bit- xxxx@gmail.com, i get an error:
"syntax error on token "@",.expected"
can someone tell me how to fix this?
 
neoedmund
Posts:53
Registered: 7/13/01
Re: JavaMail send a mail through a Proxy Server..(answer) and with Gmail(S   
Mar 26, 2006 6:43 PM (reply 5 of 19)  (In reply to original post )

 
hi, your code use a socks proxy,
but how to use a http proxy?
anybody knows?
thanks.
 
bshannon
Posts:4,225
Registered: 10/27/97
Re: JavaMail send a mail through a Proxy Server..(answer) and with Gmail(S   
Mar 26, 2006 9:29 PM (reply 6 of 19)  (In reply to #5 )

 
JavaMail uses mail protocols - SMTP, IMAP, POP.
These protocols are peers of HTTP. They don't layer
on top of HTTP. Thus, an HTTP proxy is of no use
with mail protocols.

SOCKS, on the other hand, works at a lower level than
all of these protocols.
 
neoedmund
Posts:53
Registered: 7/13/01
Re: JavaMail send a mail through a Proxy Server..(answer) and with Gmail(S   
Mar 27, 2006 7:28 PM (reply 7 of 19)  (In reply to #6 )

 
do you know about http proxy CONNECT ?
i think this can do the tunnel, if i can pass socket object to javamail, it can work.
but i didn't find a way.
 
jitendravedi
Posts:110
Registered: 9/15/00
Re: JavaMail send a mail through a Proxy Server..(answer) and with Gmail(SSL)   
Mar 29, 2006 2:53 AM (reply 8 of 19)  (In reply to original post )

 
Your code's gr8 & thx for sharing it.

I tried ur send mail code on my proxy.

It works like a charm.

However, when I run it on a proxy client, I get the following:

DEBUG SMTP: exception reading response: javax.net.ssl.SSLException: java.lang.NullPointerException
Exception in thread "main" javax.mail.MessagingException: Exception reading response
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1427)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1225)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:340)
at javax.mail.Service.connect(Service.java:297)
at javax.mail.Service.connect(Service.java:156)
at javax.mail.Service.connect(Service.java:105)
at javax.mail.Transport.send0(Transport.java:168)
at javax.mail.Transport.send(Transport.java:98)
at com.apna.beans.ForumMail.main(ForumMail.java:56)
Caused by: javax.net.ssl.SSLException: java.lang.NullPointerException
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:166)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1476)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1443)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1426)
at com.sun.net.ssl.internal.ssl.AppInputStream.read(AppInputStream.java:86)
at com.sun.mail.util.TraceInputStream.read(TraceInputStream.java:97)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
at java.io.BufferedInputStream.read(BufferedInputStream.java:235)
at com.sun.mail.util.LineInputStream.readLine(LineInputStream.java:75)
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1405)
... 8 more
Caused by: java.lang.NullPointerException
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.getHost(SSLSocketImpl.java:1656)
at com.sun.net.ssl.internal.ssl.Handshaker.getHostSE(Handshaker.java:190)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.getKickstartMessage(ClientHandshaker.java:722)
at com.sun.net.ssl.internal.ssl.Handshaker.kickstart(Handshaker.java:522)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.kickstartHandshake(SSLSocketImpl.java:1101)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1024)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:675)
at com.sun.net.ssl.internal.ssl.AppInputStream.read(AppInputStream.java:75)
... 13 more
Java Result: 1

Any ideas how I can run the program on my proxy client?
 
neoedmund
Posts:53
Registered: 7/13/01
Re: JavaMail send a mail through a Proxy Server..(answer) and with Gmail(S   
Mar 29, 2006 10:55 PM (reply 9 of 19)  (In reply to #7 )

 
see this is my code to send email to gmail using port 587 cross a http proxy,
it's done by socket and sslsocket, i don't know how to do by javamail
CONNECT smtp.gmail.com:587 HTTP/1.1
Host: smtp.gmail.com:587
 
HTTP/1.0 200 Connection established
S:220 mx.gmail.com ESMTP z80sm468366pyg
C:EHLO neoedmund
S:250-mx.gmail.com at your service
S:250-SIZE 20971520
S:250-8BITMIME
S:250-STARTTLS
S:250 ENHANCEDSTATUSCODES
C:STARTTLS
S:220 2.0.0 Ready to start TLS
[D]Cipher suite used = SSL_RSA_WITH_RC4_128_MD5
[D]Protocol = TLSv1
[D]com.sun.net.ssl.internal.ssl.AppOutputStream@1551f60
C:AUTH LOGIN
S:334 VXNlcm5hbWU6
C:(XXXXXXXXXX my base64 user)
S:334 UGFzc3dvcmQ6
C:(XXXXXXXXXX my base64 pass)
S:235 2.7.0 Accepted
C:MAIL FROM:<neoedmund@gmail.com>
S:250 2.1.0 OK
C:RCPT TO:<neoedmund@gmail.com>
S:250 2.1.5 OK
C:DATA
S:354 Go ahead
C:From: neoe <neoedmund@gmail.com>
To: neoe <neoedmund@gmail.com>
Subject: =?UTF-8?B?5L2g5aW977yM5rWL6K+V?=
MIME-Version: 1.0
Content-Type: text/plain;charset=UTF8
Content-Transfer-Encoding: base64
57uP6L+H5oiR5YiG5p6QLCDov5nmoLflj6/ku6XnmoQuDQo=
.
S:250 2.0.0 OK 1143701351 z80sm468366pyg
C:QUIT
 
prabu143
Posts:1
Registered: 10/24/07
Re: JavaMail send a mail through a Proxy Server..(answer) and with Gmail(SSL)   
Oct 24, 2007 7:03 AM (reply 10 of 19)  (In reply to original post )

 
Hi kanweng,
I am getting the following error when i was trying to run GmailFetch.java class.

Exception in thread "main" javax.mail.MessagingException: Connect failed;
nested exception is:
java.net.SocketException: Unconnected sockets not implemented
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:148)
at javax.mail.Service.connect(Service.java:275)
at javax.mail.Service.connect(Service.java:156)
at javax.mail.Service.connect(Service.java:105)
at com.ibm.podsmart.popmail.GmailFetch.main(GmailFetch.java:36)
Caused by: java.net.SocketException: Unconnected sockets not implemented
at javax.net.SocketFactory.createSocket(SocketFactory.java:2)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:222)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:163)
at com.sun.mail.pop3.Protocol.<init>(Protocol.java:81)
at com.sun.mail.pop3.POP3Store.getPort(POP3Store.java:201)
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:144)
... 4 more

please anyone can help me. How can I override SSLSocketFactory class.

Thanks,
 
bshannon
Posts:4,225
Registered: 10/27/97
Re: JavaMail send a mail through a Proxy Server..(answer) and with Gmail(S   
Oct 24, 2007 9:55 AM (reply 11 of 19)  (In reply to #10 )

 
There's a bug in the example code in SSLNOTES.txt.
There's a method missing. Search this
forum and you'll find the answer.
 
ernestojpg
Posts:6
Registered: 8/29/07
Re: JavaMail send a mail through a Proxy Server..(answer) and with Gmail(S   
Dec 13, 2007 5:54 AM (reply 12 of 19)  (In reply to original post )

 
Hello!

I've the same problem as jitendravedi.

When I use a Gmail account (SSL connection) on a proxy client, I get the following:

DEBUG SMTP: exception reading response: javax.net.ssl.SSLException: java.lang.NullPointerException
javax.mail.MessagingException: Exception reading response;
nested exception is:
javax.net.ssl.SSLException: java.lang.NullPointerException
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1611)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1369)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:412)
at javax.mail.Service.connect(Service.java:310)
at javax.mail.Service.connect(Service.java:169)
at javax.mail.Service.connect(Service.java:118)
at packCommunications.EmailAccount.sendEmail(EmailAccount.java:281)
at packGUI.PanelConfigConexion$9.run(PanelConfigConexion.java:633)
at java.lang.Thread.run(Thread.java:619)
Caused by: javax.net.ssl.SSLException: java.lang.NullPointerException
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:190)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1520)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1487)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1470)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1396)
at com.sun.net.ssl.internal.ssl.AppInputStream.read(AppInputStream.java:86)
at com.sun.mail.util.TraceInputStream.read(TraceInputStream.java:110)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
at java.io.BufferedInputStream.read(BufferedInputStream.java:237)
at com.sun.mail.util.LineInputStream.readLine(LineInputStream.java:88)
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1589)
... 8 more
Caused by: java.lang.NullPointerException
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.getHost(SSLSocketImpl.java:1700)
at com.sun.net.ssl.internal.ssl.Handshaker.getHostSE(Handshaker.java:198)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.getKickstartMessage(ClientHandshaker.java:833)
at com.sun.net.ssl.internal.ssl.Handshaker.kickstart(Handshaker.java:538)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.kickstartHandshake(SSLSocketImpl.java:1119)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1028)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:677)
at com.sun.net.ssl.internal.ssl.AppInputStream.read(AppInputStream.java:75)
... 13 more

However, when I use any other account without SSL transport, everything work fine. Any idea about this problem?

Thank!
 
ernestojpg
Posts:6
Registered: 8/29/07
Re: JavaMail send a mail through a Proxy Server..(answer) and with Gmail(S   
Dec 19, 2007 1:57 AM (reply 13 of 19)  (In reply to #12 )

 
Any help? :(

It look like a Java SE or JavaMail bug ....
 
bshannon
Posts:4,225
Registered: 10/27/97
Re: JavaMail send a mail through a Proxy Server..(answer) and with Gmail(S   
Dec 19, 2007 11:23 AM (reply 14 of 19)  (In reply to #13 )

 
The root exception is clearly coming from the
Java SE SSL code. You might want to try
asking for help in one of the Java SE forums.
You might also want to try some of the
debugging techniques described in SSLNOTES.txt.
 
This topic has 19 replies on 2 pages.    1 | 2 | Next »
Back to Forum
 
Read the Developer Forums Code of Conduct

Click to email this message Email this Topic

Edit this Topic
  
 
 
Forums Statistics
    Users Online : 24
  • Guests : 134

About Sun forums
  • Sun Forums is a large collection of user generated discussions. It is here to help you ask questions, find answers, and participate in discussions.

    Check out our guide on Getting started with Sun Forums for a full walkthrough of how to best leverage the benefits of this community.

Powered by Jive Forums