Sunday, June 23, 2013

Sent Email using Java



Sent Email using Java and gmail



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

public class Mail {

public static void main(String[] args) {

// Set up the SMTP server.
String to = "mailId";// Reciver Address.
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
props.setProperty("mail.smtp.port", "587");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("yourEmailId", "password");// SenderID and Password.
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("SenderMailId"));// Sender Id.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
to));
message.setSubject("Mail Subject");
message.setText("Mail Body");
// send message.
Transport.send(message);
System.out.println("message sent successfully");
} catch (MessagingException e) {
throw new RuntimeException(e);

}

}
}


2 comments: