Search This Blog

Email code in java

We can email anyone on any domain from our local PC with help of smtp server e.g. QK smtp server which is available free. You can find it here.


Now lets digg into java code, but before that you will need some jar files activation.jar and mail.jar from getjar.com


class Main{

public static void main(String args[]){
 try{
           String toemailId="touserId@domain.com";
           String fromemailId="fromuserId@domain.com";
           String subject="Test email";
           String body="This is a test email"; 
          
           //Get system properties
           Properties props = System.getProperties();

           //Specify the desired SMTP server
           props.put("mail.smtp.host", "localhost");

           // create a new Session object
           Session session = Session.getInstance(props,null);

           // create a new MimeMessage object (using the Session created above)
           Message message = new MimeMessage(session);
           message.setFrom(new InternetAddress(fromemailId);
           message.setRecipients(Message.RecipientType.TO, new InternetAddress[] { new InternetAddress(fromemailId });
           message.setSubject(subject);
           message.setContent(body, "text/plain");
           Transport.send(message);

           }catch(Exception e){
            System.out.println(e); 
           }
}

No comments:

Post a Comment