Friday, April 30, 2010

JAVA: Send email from JAVA? Can OR Not?

* Warning: Technical Entry


Salam and good day,

We meet again in another Technical topic. This time it's about JAVA Mail. In this tutorial, we'll use javamail api. Cut the crap now and get ready.


Pre-requisites:
Step-by-step guide:
0. Import the required library onto your project folder. (Use of IDE also can ma: Right click, import libraries, yada yada yada, you know the drill)

1. Create your function that send mail from your service more-or-less like this.
      //Declare this on class header  
   private static final String SMTP_AUTH_USER = "someemailaccount";
   private static final String SMTP_AUTH_PWD = "someemailpassword";
   
   public void postMail(String[] recipients, String subject, String message, 
                         String from, String portalUserName, 
                         String feedbackType) throws MessagingException {
        logger.info("Inside postMail");
        boolean debug = false;

        //Set the host smtp address
        Properties props = new 
        props.put("mail.smtp.host", "email.test.gov.
        props.put("mail.smtp.auth", "true");

        Authenticator auth = new SMTPAuthenticator();
        // create some properties and get the default Session
        Session session = Session.getInstance(props, auth);
        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("Feedback Type: " + feedbackType, 
                     // "\nAs reported by " + portalUserName + ".");
        String header = 
            "Portal KPT telah menerima maklumbalas seperti berikut:\n\n";
        String namaPengadu = "Nama: " + portalUserName;
        String emailPengadu = "\nEmel: " + from;
        String kategoriAduan = "\nKategori: " + feedbackType;
        String keterangan = "\nKeterangan: \n\n" + message;
        String footer = 
            "\n\n---\nIni adalah emel janaan automatik. Sebarang kemusykilan teknikal tentang maklumbalas ini boleh emel ke test@test.test.my.";
        message = 
                header + namaPengadu + emailPengadu + kategoriAduan + keterangan + 
                footer;
        //message = message;
        // Setting the Subject and Content Type
        msg.setSubject(subject);
        msg.setContent(message, "text/plain");
        Transport.send(msg);
        logger.info("Leaving postMail");
    }

    private class SMTPAuthenticator extends javax.mail.Authenticator {

        public PasswordAuthentication getPasswordAuthentication() {
            String username = SMTP_AUTH_USER;
            String password = SMTP_AUTH_PWD;
            return new PasswordAuthentication(username, password);
        }
    }


2. Create String recipientAddress[] in your model. Not to forget getter and setter.
    String recipientAddress();


3. Call the function from your controller.
                   feedbackModel.setRecipientAddress({ "receiverEmail@testServer.gov.my" }); 
          feedbackService.postMail(feedbackModel.getRecipientAddress(), 
                                         "Portal Feedback: "+feedbackModel.getPortalUserName()+"- "+feedbackModel.getFeedbackType(), 
                                         feedbackModel.getFeedbackMessage(), 
                                         feedbackModel.getPortalUserEmail(), 
                                         feedbackModel.getPortalUserName(),
                                         feedbackModel.getFeedbackType());
4. Compile and test send an email.

5. Check your email. make sure that the email is sent.

6. Tada!! my work is done!

As usual. Any comment are highly appreciated?

4 comments:

StingRay said...

nak ngantor surat pun berjela-jela.


masuk dalam peti pos udah.Senang saja.


keh keh keh..

k0m4nd3r said...

Nampak je susah.. Sebenarnya kopipes aja.. :D Hehehe.. Work smart maa.. ape nk buat.. kerja jadi researcher kene lah begini.. Hua hua hua!!

rahman said...

kopipes?tak bole pon..

k0m4nd3r said...

Cannot aa? Have you turned on your computer? :D