Welcome Message

Hi, welcome to my website. This is a place where you can get all the questions, puzzles, algorithms asked in interviews and their solutions. Feel free to contact me if you have any queries / suggestions and please leave your valuable comments.. Thanks for visiting -Pragya.

June 7, 2010

Simple java Program for sending mails

package com.abc;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class SendingEmail {
public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException
{
boolean debug = false;

//Set the host smtp address
java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Properties props = new Properties();
// props.put("mail.smtp.host", "smtp.mta"); // MS smtp
props.put("mail.smtp.host", "smtp.gmail.com"); // airtel smtp
props.put("mail.smtp.starttls.enable","true");
// create some properties and get the default Session
Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);

// create a message
Message msg = new MimeMessage(session);

// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);

InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++)
{
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);


// Optional : You can also set your custom headers in the Email if you Want
msg.addHeader("MyHeaderName", "myHeaderValue");

// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
}
}

Main Class :


package com.abc;

import javax.mail.*;

public class SendMailMain {

/**
* @param args
*/
public static void main(String[] args) {

SendingEmail sm = new SendingEmail();
String[] recep = {"zzzz.yyyy@yahoo.co.in"};
try{
sm.postMail(recep, "HI", "From ABC", "mmmm.nnnn@gmail.com");
}catch (MessagingException e) {
e.printStackTrace();
}
}

}


The idea behind this is that some SMTP servers (like gmail smtp) require authentication. So, you need to provide your credentials for them.
But for some SMTP servers (e.g. smtp.mta ) are open for all where in anyone can send mail from any id to any id, without any authentication required.


So, for the servers which requrie authentication,
u need to add the below code :


static class PopupAuthenticator extends Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("UserName", "Password");
}
}

This is extending abstract Authenticator class and overriding the getPasswordAuthentication() method.


Refer : http://forums.sun.com/thread.jspa?threadID=345884

No comments: