Sponsered Links
Categories
Sponsered Links

Mail Sender Servlet

 

This example shows how to create a servlet which is able to send mail to a specific email-id.

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

public class SimpleMailSender{
    public static void main(String args[]){
        try{
            String strstrSmtpServer=args[0];
            String strTo=args[1];
            String strFrom=args[2];
            String strSubject=args[3];
            String strBody=args[4];
            send(strstrSmtpServer, strTo, strFrom, strSubject, strBody);
        }catch (Exception ex){
            System.out.println("Usage: java SimpleMailSender"+" strstrSmtpServer toAddress fromAddress subjectText bodyText");
        }
        System.exit(0);
    }

    public static void send(String strSmtpServer, String strTo, String strFrom, String strSubject, String strBody){
        try{
            java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            Properties p = new Properties(System.getProperties());
            if(strSmtpServer != null){
                p.put("mail.smtp.starttls.enable","true");
                p.put("mail.smtp.host", strSmtpServer);
                p.put("mail.transport.protocol", "smtp");
                p.put("mail.smtp.starttls.enable","true");
                p.put("mail.smtp.auth", "true");
            }
            Session session = Session.getDefaultInstance(p, null);
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(strFrom));
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(strTo, false));
            msg.setSubject(strSubject);
            msg.setText(strBody);
            msg.setHeader("X-Mailer", "KogentEmail");
            msg.setSentDate(new Date());
            Transport.send(msg);
            System.out.println("Message sent OK.");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

 
 
Sponsered Links
Latest Updates
 
All Content of this site is for learning only. We do not warrant the correctness of its content. The risk from using it lies entirely with the user. While using this site, you agree to have read and accepted our terms of use and privacy policy.
Copyright © 2009 JSPSERVLETTUTORIAL.INFO All Right Reserved