1
votes

I can't seem to figure out how to send html emails with java :( :( I read the tutorials and ended up with this code:

Properties props = new Properties();

    props.put("mail.smtp.host", smtpServer);
    props.put("mail.smtp.socketFactory.port", SSLPort);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", SSLPort);

    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, pass);
        }
    });

    try {
        Message message = new MimeMessage(session);

        message.setFrom(new InternetAddress(baseEmail));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailTO));
        message.setSubject(emailSubject);
        message.setContent(schemeParsed, "text/html" ); //; charset=" + charset);
        message.setSentDate(new Date());
        Transport.send(message); 

which sends a message. I tested with:

big caption

but instead I received plain text:
<html><body><h2>big caption</h2></body></html>

MIME-Version: 1.0 Content-Type: text/html; charset=us-ascii Content-Transfer-Encoding: 7bit X-WP-AV: skaner antywirusowy poczty Wirtualnej Polski S. A. X-WP-SPAM: NO 0000000 [8ZJt]

the above got added by my email server (somehow). And... that's it. Can't make it to work. Any help?

2

2 Answers

1
votes

I had the same issue, but it is actually a very simple fix. All you have to do is change

message.setContent(schemeParsed, "text/html" ); //; charset=" + charset);

to

message.setText(schemeParsed, "utf-8", "html"); 

Then everything should work. If you think there might be an issue with your variable, here is all of my code.

import java.io.UnsupportedEncodingException;
import java.util.*;

import javax.mail.*;
import javax.mail.internet.*;

public class Drivers {

    static Scanner scanly = new Scanner(System.in);
    public static String username = "[email protected]";
    public static String name = "";
    public static String password = "your-password";
    public static String recipient = "";
    public static String subject = "";
    public static String emessage = "";
    public static String answer = "";
    public static String count = "";
    public static String wait = "";
    public static boolean loop = true;
    public static int countint;
    public static int waitint;

    public static void main(String[] args) throws UnsupportedEncodingException, InterruptedException {

        print("Hi! Welcome! Please begin by entering the recipient: ");
        recipient = scanly.nextLine();
        print("What would you like your name to be?");
        name = scanly.nextLine();
        print("What would you like the subject line to be?");
        subject = scanly.nextLine();
        print("Please enter the message:");
        emessage = scanly.nextLine();

        Properties props = new Properties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", "smtp.mail.yahoo.com");
        props.put("mail.smtp.port", "25");

        Session session = Session.getInstance(props,
          new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
          });

        print("Recipient: " + recipient + "\nSubject: " + subject + "\nMessage: " + emessage);

        while(loop)
        {
            print("Type 's' to send the message, 'c' to cancel, 'n' to change the message/subject, or 'sp' to choose how many.");
            answer = scanly.nextLine(); 
            if(answer.toLowerCase().equals("s"))
            {
                print("Establishing connection..");
                MimeMessage message = new MimeMessage(session);
                try {
                    print("Setting up defaults..");
                    message.setFrom(new InternetAddress(username, name));
                    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
                    message.setSubject(subject);
                    message.setText(emessage, "utf-8", "html"); 
                    print("Sending..");
                    Transport.send(message);
                } catch (MessagingException e) {
                    e.printStackTrace();
                }

                print("Sent!");
                print("Pausing..");

            } else if(answer.toLowerCase().equals("c")) {
            print("Bye!");
                System.exit(0);
            } else if(answer.toLowerCase().equals("n")) {
                main(args);
            } else if(answer.toLowerCase().equals("sp"))
            {
                print("How many times?");
                count = scanly.nextLine();
                countint = Integer.parseInt(count);
                print("What would you like the wait time to be? (Recommended is 4000-10000)");
                wait = scanly.nextLine();
                waitint = Integer.parseInt(wait);
                for (int i = 0; i < countint; 
                {
                    print("Establishing connection..");
                    Message message = new MimeMessage(session);
                    try {
                        print("Setting up defaults..");
                        message.setFrom(new InternetAddress(username, name));
                        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
                        message.setSubject(subject);
                        message.setText(emessage); 
                        print("Sending..");
                        Transport.send(message);
                    } catch (MessagingException e) {
                        e.printStackTrace();
                    }

                    print("Sent!");
                    Thread.sleep(waitint);
                }
            } else
            {
                print("Error..");
            }
        }

    }

    public static void print(String ttp)
    {
        System.out.println(ttp);
    }

}

Anyway, if there is any issue or anything, email me at [email protected]

0
votes

Does this work?

MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setText(unescapeHtml(messageString));
multipart.addBodyPart(bodyPart);

Here, unescapeHtml(...) is some unescape method of your choice and MimeBodyPart is javax.mail.internet.MimeBodyPart where I assume you are already using javax.mail.internet.MimeMessage