2

I have a simple web application where different users can log into it. One of the important feature is user can access a document and send email of it's content to an outsider like third party. Below is just how the email looks like to give an idea:

enter image description here

It's pretty self explanatory and I can send to multiple user if I want like abc@example.com,efg@hotmail.com,... in the field box shown.With all this, I am using Java Mail API to make it work and after hitting the send button,it sends directly to the recipient.No issue at all.

Now, I want to modify this by doing this email feature as a service.What this means is when I send the email,the content and info filled in will be stored in a table in MYSQL and the service(running in background) will pick up from the table and do the sending.

This is my function:

public void sendEmail(String recipient, String subject, String content,
                      String host, String port, final String senderaddress, 
                      final String password) {
    try {
        System.out.println("Please Wait, sending email...");

        /*Setup mail server */
        Properties props = new Properties();
        props.put("mail.smtp.host", host); //SMTP Host
        props.put("mail.smtp.port", port); //TLS Port
        props.put("mail.smtp.auth", "true"); //enable authentication
        props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS
        //create Authenticator object to pass in Session.getInstance argument
        Authenticator auth = new Authenticator() {
            //override the getPasswordAuthentication method
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(senderaddress, password);
            }
        };
        Session session = Session.getInstance(props, auth);
        session.setDebug(true);

        // Define message
        MimeMessage message = new MimeMessage(session);
        // Set From: header field of the header.
        message.setFrom(new InternetAddress(senderaddress));
        message.addRecipients(Message.RecipientType.TO,
                              InternetAddress.parse(recipient));
        // Set Subject: header field
        message.setSubject(subject);

        // Now set the actual message
        message.setText(content);
        try {
            Transport.send(message);
        } catch (AddressException addressException) {
            addressException.printStackTrace();
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

Can this be done in the way I want because I am unsure how to make it work?

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
Daredevil
  • 1,672
  • 3
  • 18
  • 47
  • 1
    As I understand your main application saves it and does not call the send email service? You can use a [scheduled task](https://stackoverflow.com/questions/7814089/how-to-schedule-a-periodic-task-in-java) to pick up newly saved emails and send them. – Cray Apr 09 '19 at 04:45
  • (Oh I get it. This question is not about the code you have posted. It is about the code that you haven't written yet. Question: why did you include that code ... if it is not relevant to your question?) – Stephen C Apr 09 '19 at 04:50
  • Answer: yes it can be done in the way you want. 1) Periodically query the database to extract emails to be sent. 2) Send each row in turn. 3) Send email. 4) Delete row or mark row as sent. Note that this does not guarantee that the emails will actually be delivered, and doesn't deal with email addresses that may be incorrectly formatted. – Stephen C Apr 09 '19 at 04:55
  • @Cray Yes that is correct, can you eleborate more? Because I plan to create another module (main,java) to handle this as a service. – Daredevil Apr 09 '19 at 05:34
  • @StephenC Yes it's about the code i have not written. I figured including the code would give an idea of how I am sending the email directly. – Daredevil Apr 09 '19 at 05:35
  • @StephenC I see. I have yet created the table and thinking how many columns would be suitable for this case? – Daredevil Apr 09 '19 at 05:36
  • Well you have 2 things to do: 1. save emails to DB, 2. scheduled email sender. Do some research on how to do either of them and if you get errors ask for help. – Cray Apr 09 '19 at 05:39
  • One column for each of the email-specific fields (e.g. subject, recipient, content, etc) plus columns for recording a unique id, timestamps and status. You should be able to work it our from your requirements. – Stephen C Apr 09 '19 at 05:47
  • I see. From the design stand point if the service picks up the email and sent,then that record shall be deleted from that table, no reason for status,timestamp,etc. Is the content column going to be a problem if the message is long? – Daredevil Apr 09 '19 at 05:50
  • That depends on the database, and the type you use for the column. For MySQL a `varchar` column can be up to 4096 characters. Beyond that you will need to use a `clob` which gets more complicated. But you really need to start looking these things up for yourself in the MySQL documentation, the JDBC documentation (or a tutorial) etcetera. – Stephen C Apr 09 '19 at 05:56

1 Answers1

2

1 ) After hitting Sending mail button from UI, You need to call a method for saving data like recipient, subject, content in DB

2)Write an email sender Service which retrieves non_delivered / pending mail from DB table and send it through Java Mail API

3)Scheduled email sender service with the help of ScheduledExecutorService

Ajinkya
  • 325
  • 3
  • 12
  • What columns should i have in my table? – Daredevil Apr 09 '19 at 06:06
  • @Daredevil you can make column like recipient, subject, content , mailStaus – Ajinkya Apr 09 '19 at 06:08
  • Is mailstatus neccesary? I thought after schedueling the service,it will delete the record from the table after sending. – Daredevil Apr 09 '19 at 06:10
  • 1
    @Daredevil the column mailStatus can have value **Delivered** (if mail sender service sends already called ) or **Pending** (if record is new and mail sender Service is yet to call for that record) – Ajinkya Apr 09 '19 at 06:12
  • So there is no need to delete the records when the data is pumped into the table? – Daredevil Apr 09 '19 at 06:13
  • @Daredevil if you are deleting the record after sending then no need for mailStatus Column , But Its very relible for you if you store records for certain time in DB even after sendig mail (You can write a different Service to delete old record from DB and Seculed it weekly ) – Ajinkya Apr 09 '19 at 06:18
  • Which approach is better? – Daredevil Apr 09 '19 at 06:19
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/191499/discussion-between-ajinkya-and-daredevil). – Ajinkya Apr 09 '19 at 06:19