Skip to Main Content

Java EE (Java Enterprise Edition) General Discussion

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

JavaMail send a mail through a Proxy Server..(answer) and with Gmail(SSL)

843830Apr 10 2005 — edited Jun 28 2010
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.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);
      } 
   }
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 26 2010
Added on Apr 10 2005
21 comments
54,477 views