Google engine for JAVA applications: how to embed html in mail sent when using java mail api in Google engine?

this is the working code that I use to send mail, but if I include html content in the string argument of the setText () method, then it displays just like a string for the user, has no HTML effect.

Message msg = new MimeMessage(session1); msg.setFrom(new InternetAddress(" abc@xyz.com ", "Team Application")); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, "Dear "+name1+".")); msg.setSubject("Registration confirmation mail"); msg.setText("Dear "+name1+",\nThanks for registering with us."); Transport.send(msg); 
+6
source share
3 answers

try using setContent instead of setText
so for your example code:

  Message msg = new MimeMessage(session1); msg.setFrom(new InternetAddress(" abc@xyz.com ", "Team Application")); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, "Dear "+name1+".")); msg.setSubject("Registration confirmation mail"); msg.setContent("Dear <i>"+name1+"</i>,<br>Thanks for registering with us.", "text/html"); Transport.send(msg); 

Personally, I use a multi-page message with text and an html version. This is part of my own code:

  // Unformatted text version final MimeBodyPart textPart = new MimeBodyPart(); textPart.setText("plain content"); // HTML version final MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent("<b>html content</b>", "text/html"); // Create the Multipart. Add BodyParts to it. final Multipart mp = new MimeMultipart(); mp.addBodyPart(textPart); mp.addBodyPart(htmlPart); // Set Multipart as the message content msg.setContent(mp); 
+10
source

Checking the MimeMessage documentation, you can setText () an overloaded signature, where you can specify the encoding and subtype of Mime:

 msg.setText("Your html body", "utf-8", "html"); 
+1
source

You should use MailService.Message and MailService from the low-level API. Example:

 Message msg = new Message(); msg.setSender(_sender); msg.setTo(_recipient); msg.setSubject(_msgSubject); msg.setHtmlBody("<h1 style="height:1200px;">THIS IS RUSSIA!!!</h1>"); MailService service = MailServiceFactory.getMailService(); try { service.send(msg); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } 
+1
source

Source: https://habr.com/ru/post/892435/


All Articles