JavaMail implements a way to send a message in HTML format

  • 2020-04-01 03:52:22
  • OfStack

This article illustrates how JavaMail implements sending a message in HTML format. Share with you for your reference. The details are as follows:

Attachments are in the form of hypertext, very common, and ordinary mail, just looked up some Settings, only slightly different processing

The code is as follows:


<%@ page contentType="text/html;charset=GBK" %>
<%@ page import="java.util.*"%>
<%@ page import="javax.mail.*" %>
<%@ page import="javax.mail.internet.*"%>
<%@ page import="javax.activation.*" %>
<%
try{
 request.setCharacterEncoding("GBK");
 String from=request.getParameter("from");
 String to=request.getParameter("to");
 String subject=request.getParameter("subject");
 String messageText=request.getParameter("content");
  String password=request.getParameter("password");
 /
 //int n =from.indexOf('@');
 //int m=from.length() ;
 //String mailserver ="smtp."+from.substring(n+1,m);
  String mailserver="mrlx";
  //Use this code to specify an SMTP server for sending E-mail on a LAN
  Properties prop =new Properties();
  prop.put("mail.smtp.host",mailserver);
  prop.put("mail.smtp.auth","true");
  Session sess =Session.getInstance(prop);
  sess.setDebug(true);
  MimeMessage message=new MimeMessage(sess);
  //Set the recipient, sender, subject, and sending time for the message object
  InternetAddress mail_from =new InternetAddress(from);
  message.setFrom(mail_from);
  InternetAddress mail_to =new InternetAddress(to);
  message.setRecipient(Message.RecipientType.TO,mail_to);
  message.setSubject(subject);
  message.setSentDate(new Date());
  Multipart mul=new MimeMultipart();
  //Create a new MimeMultipart object to hold multiple BodyPart objects
  BodyPart mdp=new MimeBodyPart();
  //Create a new BodyPart object to hold the contents of the letter
  mdp.setContent(messageText,"text/html;charset=GBK");
  mul.addBodyPart(mdp);
  //Add the BodyPart containing the contents of the letter to the MimeMulitipart object
  message.setContent(mul);
  //Make the mul the content of the message object
  message.saveChanges();
  Transport transport = sess.getTransport("smtp");
  //The first parameter is the SMTP address of the mail server used to send the mail.
  //The second parameter is the username and the third parameter is the password
  transport.connect(mailserver,from,password);
  transport.sendMessage(message,message.getAllRecipients());
  transport.close();
  out.println("<script language='javascript'>alert(' Email sent! ');window.location.href='index.jsp';</script>");
}catch(Exception e){
 System.out.println(" Error sending email: "+e.getMessage());
 out.println("<script language='javascript'>alert(' Email failed! ');window.location.href='index.jsp';</script>");
}
%>

I hope this article has been helpful to your Java programming.


Related articles: