user1504940
user1504940

Reputation: 175

how to send mail from glassfish server?

How to write a mail application with java mail API that run all time at glassfish server and search a specific time in the database and send mail at that time. i have web application written in JSF that need to send mail at specific time given in database.

Upvotes: 1

Views: 5100

Answers (1)

Fahim Parkar
Fahim Parkar

Reputation: 31637

For gmail, use below code

import org.apache.commons.mail.*;

public class GmailEmailWorking {

    public static void main(String[] args) {
        String myEmailId = "[email protected]";
        String myPassword = "password";
        String senderId = "[email protected]";
        try {
            MultiPartEmail email = new MultiPartEmail();
            email.setSmtpPort(587);
            email.setAuthenticator(new DefaultAuthenticator(myEmailId, myPassword));
            email.setDebug(true);
            email.setHostName("smtp.gmail.com");
            email.setFrom(myEmailId);
            email.setSubject("Hi");
            email.setMsg("This is a test mail ... :-)\n\nPlease check attachements that I have sent.\n\nThanks,\nFahim");
            email.addTo(senderId);
            email.setTLS(true);

            EmailAttachment attachment = new EmailAttachment();
            attachment.setPath("/Users/fahadparkar/Desktop/Fahim/tables.xlsx");
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            attachment.setDescription("Excel");
            attachment.setName("tables.xlsx");
            email.attach(attachment);

            email.send();
            System.out.println("Mail sent!");
        } catch (Exception e) {
            System.out.println("Exception :: " + e);
        }
    }
}

Below are list of jar files you will need

To send from other server, you will need to do changes at below line

email.setSmtpPort(587);
email.setHostName("smtp.gmail.com");

Upvotes: 2

Related Questions