Friday, November 26, 2010

Sending an Email

 java.util.Properties props = new java.util.Properties();  
 props.put("mail.smtp.host", "here you have to give the smtp host address");  
 props.put("mail.smtp.port", "smtp port number, it may or may not required");  
 Session session = Session.getDefaultInstance(props, null);  
 // Construct the message  
 try {  
      Message msg = new MimeMessage(session);  
      String emailfrom=request.getParameter("emailfrom");  
      String emailto=request.getParameter("emailto");  
      String comment="Hi there";  
      msg.setContent(comment,"text/html");  
      msg.setFrom(new InternetAddress(request.getParameter("emailfrom")));  
      msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(request.getParameter("emailto")));  
      msg.setSubject("Enter the subject here");  
      msg.setSentDate(new Date());  
      // Sends the message  
      Transport.send(msg);  
      response.getWriter().print("success");  
 } catch (AddressException e) {  
      // TODO Auto-generated catch block  
      response.getWriter().print("failed");  
      e.printStackTrace();  
 } catch (MessagingException e) {  
      // TODO Auto-generated catch block  
      response.getWriter().print("failed");  
      e.printStackTrace();  
 }  

No comments: