[ACCEPTED]-how to send HTML email-jakarta-mail

Accepted answer
Score: 121

Don't upcast your MimeMessage to Message:

MimeMessage simpleMessage = new MimeMessage(mailSession);

Then, when you want 8 to set the message body, either call

simpleMessage.setText(text, "utf-8", "html");

or call

simpleMessage.setContent(text, "text/html; charset=utf-8");

If 7 you'd rather use a charset other than utf-8, substitute 6 it in the appropriate place.

JavaMail has 5 an extra, useless layer of abstraction that 4 often leaves you holding classes like Multipart, Message, and 3 Address, which all have much less functionality 2 than the real subclasses (MimeMultipart, MimeMessage, and InternetAddress) that 1 are actually getting constructed...

Score: 0

Here is my sendEmail java program. It's 2 good to use setContent method of Message 1 class object.

message.setSubject(message_sub);
message.setContent(message_text, "text/html; charset=utf-8");

sendEmail.java

package employee;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

public class SendEmail {

    public static void sendEmail(String message_text, String send_to,String message_sub ) throws UnsupportedEncodingException {

        
        final String username = "hello@xyz.com";
        final String password = "password";

        Properties prop = new Properties();
        prop.put("mail.smtp.host", "us2.smtp.mailhostbox.com"); //replace your host address.
        prop.put("mail.smtp.port", "587");
        prop.put("mail.smtp.auth", "true");
        prop.put("mail.smtp.starttls.enable", "true"); //TLS
        
        Session session = Session.getInstance(prop,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("sender@xyz.com", "Name from which mail has to be sent"));
            message.setRecipients(
                    Message.RecipientType.TO,
                    InternetAddress.parse(send_to)
            );
            message.setSubject(message_sub);
            message.setContent(message_text, "text/html; charset=utf-8");
            
          

            Transport.send(message);

            System.out.println("Done");

        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

}

More Related questions