skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Monday, October 22, 2012

Send a mail from SMTP server using Java Mail

Posted by Raju Gupta at 1:55 AM – 0 comments
 
This code allows the user to login to his/her mail account to send a mail to another recepient.First the code needs to be configured by entering the Server details and user credentials .This code authenticates the user and creates a session then a MimeMessage Object is created where the subject and content of the mail is set.

public class SmtpMail{
 public static void main(String[] args) 
 {
  Properties props = new Properties();
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.starttls.enable", "true");
  props.put("mail.smtp.host", "smtp.gmail.com");
  props.put("mail.smtp.port", "587");
  final String username = "Username@gmail.com";
  final String password = "Password";
  Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
 protected PasswordAuthentication getPasswordAuthentication() {
   return new PasswordAuthentication(username, password);
  }
  });
try {
   Message message = new MimeMessage(session);
   message.setRecipients(Message.RecipientType.TO,
    InternetAddress.parse("toEmailAddress@yahoo.com"));
   System.out.println(session.toString());
   message.setSubject("JavaMail Subject");
   message.setText("Dear Recepient,"
    + "\n\n This is a Test Mail");
   System.out.println(session.toString());
   Transport.send(message);
   System.out.println("Done");
 
  } catch (MessagingException e) {
   throw new RuntimeException(e);
  }
 }
}


Labels: Email Example , Java Mail Examples

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger