下面列出了javax.mail.internet.MimeMessage#setSubject ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Listen for e-mail requests through CDI events and send the message
*
* @param mailMessage the message to send
* @throws Exception if any problem occur in the process
*/
public void send(@Observes MailMessage mailMessage) throws Exception {
final MimeMessage message = new MimeMessage(this.mailSession);
// message header
message.setFrom(mailMessage.getFrom());
message.setSubject(mailMessage.getTitle());
message.setRecipients(Message.RecipientType.TO, mailMessage.getAddressees());
message.setRecipients(Message.RecipientType.CC, mailMessage.getCcs());
// message body
message.setText(mailMessage.getContent(), "UTF-8", "html");
message.setSentDate(new Date());
// send
Transport.send(message);
}
/**
Activate the specified options, such as the smtp host, the
recipient, from, etc. */
public
void activateOptions() {
Session session = createSession();
msg = new MimeMessage(session);
try {
addressMessage(msg);
if(subject != null) {
msg.setSubject(subject);
}
} catch(MessagingException e) {
LogLog.error("Could not activate SMTPAppender options.", e );
}
if (evaluator instanceof OptionHandler) {
((OptionHandler) evaluator).activateOptions();
}
}
/**
* Listen for e-mail requests through CDI events and send the message
*
* @param mailMessage the message to send
* @throws Exception if any problem occur in the process
*/
public void send(@Observes MailMessage mailMessage) throws Exception {
final MimeMessage message = new MimeMessage(this.mailSession);
// message header
message.setFrom(mailMessage.getFrom());
message.setSubject(mailMessage.getTitle());
message.setRecipients(Message.RecipientType.TO, mailMessage.getAddressees());
message.setRecipients(Message.RecipientType.CC, mailMessage.getCcs());
// message body
message.setText(mailMessage.getContent(), "UTF-8", "html");
message.setSentDate(new Date());
// send
Transport.send(message);
}
public MimeMessage createMessage(String from, String to, String subject, String body)
throws MessagingException {
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipients(TO, to);
msg.setSubject(subject);
msg.setContent(msg, "text/plain");
msg.setSentDate(new Date());
msg.setText(body);
msg.setSender(new InternetAddress(from));
msg.setReplyTo(new InternetAddress[]{new InternetAddress(from)});
return msg;
}
protected MimeMessage newEmailTo(Session session, String recipient, String subject) throws MessagingException {
MimeMessage message = new MimeMessage(session);
InternetAddress[] to = {new InternetAddress(recipient)};
message.setRecipients(Message.RecipientType.TO, to);
message.setSubject(subject);
return message;
}
public void testFetchBigMessage() throws IOException, MessagingException {
testCreateFolder();
// create 10MB message
MimeMessage mimeMessage = new MimeMessage((Session) null);
mimeMessage.addHeader("to", Settings.getProperty("davmail.to"));
mimeMessage.addHeader("bcc", Settings.getProperty("davmail.bcc"));
Random random = new Random();
StringBuilder randomText = new StringBuilder();
for (int i = 0; i < 10 * 1024 * 1024; i++) {
randomText.append((char) ('a' + random.nextInt(26)));
}
mimeMessage.setText(randomText.toString());
mimeMessage.setSubject("Big subject");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
mimeMessage.writeTo(baos);
byte[] content = baos.toByteArray();
long start = System.currentTimeMillis();
writeLine(". APPEND testfolder (\\Seen \\Draft) {" + content.length + '}');
assertEquals("+ send literal data", readLine());
writeLine(new String(content));
assertEquals(". OK APPEND completed", readFullAnswer("."));
System.out.println("Create time: " + (System.currentTimeMillis() - start) + " ms");
writeLine(". NOOP");
assertEquals(". OK NOOP completed", readFullAnswer("."));
start = System.currentTimeMillis();
writeLine(". UID FETCH 1:* (RFC822.SIZE BODY.TEXT)");
readFullAnswer(".");
System.out.println("Fetch time: " + (System.currentTimeMillis() - start) + " ms");
}
/** */
private void testEightBitMessage(String body, String charset) throws Exception
{
MimeMessage message = new MimeMessage(this.session);
message.addRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
message.setFrom(new InternetAddress("[email protected]"));
message.setSubject("hello");
message.setText(body, charset);
message.setHeader("Content-Transfer-Encoding", "8bit");
Transport.send(message);
}
@Test(expected = MockTestException.class)
public void testOnlyInbox() throws Exception {
final MockMailbox mb = MockMailbox.get("[email protected]");
final MailboxFolder mf = mb.getInbox();
final MimeMessage msg = new MimeMessage((Session) null);
msg.setSubject("Test");
msg.setFrom("[email protected]");
msg.setText("Some text here ...");
msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
mf.add(msg); // 11
mf.add(msg); // 12
mf.add(msg); // 13
mb.getRoot().getOrAddSubFolder("test").create().add(msg);
final Store store = session.getStore(Providers.getPOP3Provider("makes_no_differernce", false, true));
store.connect("[email protected]", null);
final Folder defaultFolder = store.getDefaultFolder();
try {
defaultFolder.getFolder("test");
} catch (final MessagingException e) {
throw new MockTestException(e);
}
}
@Test
public void javaMailSenderWithCustomSession() throws MessagingException {
final Session session = Session.getInstance(new Properties());
MockJavaMailSender sender = new MockJavaMailSender() {
@Override
protected Transport getTransport(Session sess) throws NoSuchProviderException {
assertEquals(session, sess);
return super.getTransport(sess);
}
};
sender.setSession(session);
sender.setHost("host");
sender.setUsername("username");
sender.setPassword("password");
MimeMessage mimeMessage = sender.createMimeMessage();
mimeMessage.setSubject("custom");
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
mimeMessage.setSentDate(new GregorianCalendar(2005, 3, 1).getTime());
sender.send(mimeMessage);
assertEquals("host", sender.transport.getConnectedHost());
assertEquals("username", sender.transport.getConnectedUsername());
assertEquals("password", sender.transport.getConnectedPassword());
assertTrue(sender.transport.isCloseCalled());
assertEquals(1, sender.transport.getSentMessages().size());
assertEquals(mimeMessage, sender.transport.getSentMessage(0));
}
@Test
public void testUidSearchTextWithCharset() throws MessagingException, IOException {
greenMail.setUser("[email protected]", "pwd");
store.connect("[email protected]", "pwd");
try {
IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
final MimeMessage email = GreenMailUtil.createTextEmail("[email protected]", "[email protected]",
"some subject", "some content",
greenMail.getSmtp().getServerSetup());
String[][] s = {
{"US-ASCII", "ABC", "1"},
{"ISO-8859-15", "\u00c4\u00e4\u20AC", "2"},
{"UTF-8", "\u00c4\u00e4\u03A0", "3"}
};
for (String[] charsetAndQuery : s) {
final String charset = charsetAndQuery[0];
final String search = charsetAndQuery[1];
email.setSubject("subject " + search, charset);
GreenMailUtil.sendMimeMessage(email);
// messages[2] contains content with search text, match must be case insensitive
final byte[] searchBytes = search.getBytes(charset);
final Argument arg = new Argument();
arg.writeBytes(searchBytes);
// Try with and without quotes
searchAndValidateWithCharset(folder, charsetAndQuery[2], charset, arg);
searchAndValidateWithCharset(folder, charsetAndQuery[2], '"' + charset + '"', arg);
}
} finally {
store.close();
}
}
protected MimeMessage getMissingEncodingMessage() throws Exception {
MimeMessage mmCreated = new MimeMessage(Session.getDefaultInstance(new Properties()));
mmCreated.setSubject("test");
MimeMultipart mm = new MimeMultipart("alternative");
mm.addBodyPart(new MimeBodyPart(new InternetHeaders(new ByteArrayInputStream("X-header: test2\r\nContent-Type: text/plain; charset=Cp1252\r\nContent-Transfer-Encoding: quoted-printable\r\n"
.getBytes())), "second part =E8=E8".getBytes()));
mmCreated.setContent(mm);
mmCreated.saveChanges();
return mmCreated;
}
public boolean send(List<String> recipients,String from,String subject,MimeMultipart content) {
if(from==null) from=defaultFrom;
if(subject==null) subject=defaultSubject;
try{
// Properties props=new Properties();
// props.put("mail.smtp.host",smtpServer);
Session session=Session.getDefaultInstance(mailProps,null);
MimeMessage message=new MimeMessage(session);
if(subject!=null) message.setSubject(subject);
if(from!=null) message.setFrom(new InternetAddress(from));
message.setContent(content);
Transport transport = session.getTransport("smtp");
if(smtpPort>0) transport.connect(smtpServer,smtpPort,smtpUser,smtpPass);
else transport.connect(smtpServer,smtpUser,smtpPass);
Address[] recipientAddresses=new Address[recipients.size()];
for(int i=0;i<recipientAddresses.length;i++){
recipientAddresses[i]=new InternetAddress(recipients.get(i));
}
transport.sendMessage(message,recipientAddresses);
return true;
}
catch(MessagingException me){
logging.warn("Couldn't send email",me);
return false;
}
}
public boolean send() {
// 创建邮件Session所需的Properties对象.API建议使用set而不是put(putall).
Properties props = new Properties();
props.setProperty("mail.smtp.host", smtpServer);
props.setProperty("mail.smtp.auth", "true");
props.put("mail.smtp.ssl.enable", "false");
props.put("mail.debug", "true");
// 创建Session对象,代表JavaMail中的一次邮件会话.
// Authenticator==>Java mail的身份验证,如QQ邮箱是需要验证的.所以需要用户名,密码.
// PasswordAuthentication==>系统的密码验证.内部类获取,或者干脆写个静态类也可以.
Session session = Session.getDefaultInstance(props,
new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
try {
// 构造MimeMessage并设置相关属性值,MimeMessage就是实际的电子邮件对象.
MimeMessage msg = new MimeMessage(session);
// 设置发件人
msg.setFrom(new InternetAddress(from));
// 设置收件人,为数组,可输入多个地址.
InternetAddress[] addresses = { new InternetAddress(to) };
// Message.RecipientType==>TO(主要接收人),CC(抄送),BCC(密件抄送)
msg.setRecipients(Message.RecipientType.TO, addresses);
msg.setSentDate(new Date());
// 设置邮件主题,如果不是UTF-8就要转换下.MimeUtility.encodeText(subject,"gb2312","B"));
// subject=translateChinese(subject);
msg.setSubject(MimeUtility.encodeText(subject,"utf8","B"));
// =====================正文部分===========
// 构造Multipart容器
Multipart mp = new MimeMultipart();
// =====================正文文字部分===========
// 向Multipart添加正文
MimeBodyPart mbpContent = new MimeBodyPart();
mbpContent.setContent(content,"text/plain;charset=gb2312");
// 将BodyPart添加到MultiPart容器中
mp.addBodyPart(mbpContent);
// =====================正文附件部分===========
// 向MulitPart添加附件,遍历附件列表,将所有文件添加到邮件消息里
if (attachments != null) {
for (String efile : attachments) {
MimeBodyPart mbpFile = new MimeBodyPart();
// 以文件名创建FileDataSource对象
FileDataSource fds = new FileDataSource(efile);
// 处理附件
mbpFile.setDataHandler(new DataHandler(fds));
mbpFile.setFileName(fds.getName());
// 将BodyPart添加到Multipart容器中
mp.addBodyPart(mbpFile);
}
attachments.clear();
}
// 向MimeMessage添加Multipart
msg.setContent(mp);
msg.setSentDate(new Date());
// 发送邮件,使用如下方法!
Transport.send(msg);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
@Override
public void send(InternetAddress address, String subject, String htmlBody)
throws AddressException, MessagingException {
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, address);
message.setSubject(subject);
message.setText(htmlBody, "UTF-8", "html");
LOG.info("Sending email:" + "\n Subject: " + subject + "\n Message body: " + htmlBody);
// Send message
Transport.send(message);
}
/**
* Send an email.
*
* @param recipient The recipient of the email
* @param subject The subject of the email.
* @param body The body of the email.
* @return true if the email was sent successfully.
*/
public boolean sendMail(final String recipient, final String subject, final String body) {
boolean result = false;
// Create a Properties object to contain connection configuration information.
java.util.Properties props = System.getProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.port", getPort());
// Set properties indicating that we want to use STARTTLS to encrypt the connection.
// The SMTP session will begin on an unencrypted connection, and then the client
// will issue a STARTTLS command to upgrade to an encrypted connection.
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.starttls.required", "true");
// Create a Session object to represent a mail session with the specified properties.
Session session = Session.getDefaultInstance(props);
// Create a message with the specified information.
MimeMessage msg = new MimeMessage(session);
Transport transport = null;
// Send the message.
try {
msg.setFrom(new InternetAddress(getSender()));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
msg.setSubject(subject);
msg.setContent(body, "text/plain");
// Create a transport.
transport = session.getTransport();
// Connect to email server using the SMTP username and password you specified above.
transport.connect(getHost(), getSmtpUsername(), getUnobfuscatedSmtpPassword());
// Send the email.
transport.sendMessage(msg, msg.getAllRecipients());
result = true;
} catch (Exception ex) {
LOGGER.error("The email was not sent.", ex);
} finally {
// Close and terminate the connection.
try {
transport.close();
} catch (MessagingException e) {
LOGGER.error("Could not close transport", e);
}
}
return result;
}
@Override
protected ModelAndView handle(HttpServletRequest request,
HttpServletResponse response, Object object, BindException exception)
throws Exception {
Admin admin = (Admin) object; //将数据封装起来
System.out.println("表单提交过来时的数据是:"+admin.toString());
if (adminService.addAdmin(admin)) { //调用该方法,将数据持久到数据库中,如果持久化成功,则发送邮件给当前的注册用户
try {
String host = "smtp.qq.com"; // 邮件服务器
String from = "[email protected]"; // 发送邮件的QQ
String authcode = "fgoobvssrkuibjhe"; // 对于QQ的个人邮箱而言,密码使用的是客户端的授权码,而不是用户的邮箱密码
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.setProperty("mail.transport.protocol", "smtp"); // 发送邮件协议名称
props.put("mail.smtp.auth", "true"); // 开启授权
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", authcode);
props.put("mail.smtp.port", "587"); // smtp邮件服务器的端口号,必须是587,465端口调试时失败
props.setProperty("mail.smtp.ssl.enable", "true");
Session session = Session.getDefaultInstance(props,
new GMailAuthenticator("[email protected]",
"fgoobvssrkuibjhe"));
props.put("mail.debug", "true");
MimeMessage message = new MimeMessage(session);
Address fromAddress = new InternetAddress(from);
Address toAddress = new InternetAddress(admin.getEmail());
message.setFrom(fromAddress);
message.setRecipient(Message.RecipientType.TO, toAddress);
message.setSubject("注册成功确认邮件");
message.setSentDate(new Date());
//发送的链接包括其写入到数据库中的UUID,也就是链接localhost:8080/Login_Sys/ActivateServlet和UUID的拼接,#连接两个字符串
//获取UUID
System.out.println(adminService.getUUID(admin));
message.setContent("<h1>恭喜你注册成功,请点击下面的连接激活账户</h1><h3><a href='http://localhost:8080/Login_Sys_Spring_SpringMVC_c3p0/Activate.action?code="+adminService.getUUID(admin)+"'>http://localhost:8080/Login_Sys_Spring_SpringMVC_c3p0/Activate</a></h3>","text/html;charset=utf-8");
Transport transport = session.getTransport();
transport.connect(host, from, authcode);
message.saveChanges();
Transport.send(message);
transport.close();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
//封装一个ModelAndView对象,提供转发视图的功能
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message", "增加管理员成功");
modelAndView.setViewName("sign_success"); //成功之后跳转到该界面,采用逻辑视图,必须要配置视图解析器
return modelAndView; //该方法一定要返回modelAndView
}
public static void send(byte[] attachment) throws AddressException, MessagingException, IOException {
Session session = Session.getDefaultInstance(new Properties());
// Create a new MimeMessage object
MimeMessage message = new MimeMessage(session);
// Add subject, from and to lines
message.setSubject(SUBJECT, "UTF-8");
message.setFrom(new InternetAddress(SENDER));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(RECIPIENT));
// Create a multipart/alternative child container
MimeMultipart msgBody = new MimeMultipart("alternative");
// Create a wrapper for the HTML and text parts
MimeBodyPart wrap = new MimeBodyPart();
// Define the text part
MimeBodyPart textPart = new MimeBodyPart();
textPart.setContent(BODY_TEXT, "text/plain; charset=UTF-8");
// Define the HTML part
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(BODY_HTML, "text/html; charset=UTF-8");
// Add the text and HTML parts to the child container
msgBody.addBodyPart(textPart);
msgBody.addBodyPart(htmlPart);
// Add the child container to the wrapper object
wrap.setContent(msgBody);
// Create a multipart/mixed parent container
MimeMultipart msg = new MimeMultipart("mixed");
// Add the parent container to the message
message.setContent(msg);
// Add the multipart/alternative part to the message
msg.addBodyPart(wrap);
// Define the attachment
MimeBodyPart att = new MimeBodyPart();
DataSource fds = new ByteArrayDataSource(attachment, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
att.setDataHandler(new DataHandler(fds));
// Set the attachment name
String reportName = "WorkReport.xls";
att.setFileName(reportName);
// Add the attachment to the message
msg.addBodyPart(att);
try {
System.out.println("Attempting to send an email through Amazon SES " + "using the AWS SDK for Java...");
Region region = Region.US_WEST_2;
SesClient client = SesClient.builder().region(region).build();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
message.writeTo(outputStream);
ByteBuffer buf = ByteBuffer.wrap(outputStream.toByteArray());
byte[] arr = new byte[buf.remaining()];
buf.get(arr);
SdkBytes data = SdkBytes.fromByteArray(arr);
RawMessage rawMessage = RawMessage.builder()
.data(data)
.build();
SendRawEmailRequest rawEmailRequest = SendRawEmailRequest.builder()
.rawMessage(rawMessage)
.build();
client.sendRawEmail(rawEmailRequest);
} catch (SdkException e) {
e.getStackTrace();
}
// snippet-end:[ses.java2.sendmessageattachment.main]
}
/**
* 发送邮件(负载均衡)
*
* @param key 负载均衡key
* @param to 收件人,多个收件人用 {@code ;} 分隔
* @param cc 抄送人,多个抄送人用 {@code ;} 分隔
* @param bcc 密送人,多个密送人用 {@code ;} 分隔
* @param subject 主题
* @param content 内容,可引用内嵌图片,引用方式:{@code <img src="cid:内嵌图片文件名" />}
* @param images 内嵌图片
* @param attachments 附件
* @return 如果邮件发送成功,则返回 {@code true},否则返回 {@code false}
*/
public boolean sendByLoadBalance(String key, String to, String cc,
String bcc, String subject, String content,
File[] images, File[] attachments){
log.info("loadBalanceKey={}", key);
Properties properties = MailManager.getProperties(key);
log.info("properties={}", properties);
Session session = MailManager.getSession(key);
MimeMessage message = new MimeMessage(session);
String username = properties.getProperty("mail.username");
ThreadLocalUtils.put(Constants.CURRENT_MAIL_FROM, username);
try {
message.setFrom(new InternetAddress(username));
addRecipients(message, Message.RecipientType.TO, to);
if (cc != null) {
addRecipients(message, Message.RecipientType.CC, cc);
}
if (bcc != null) {
addRecipients(message, Message.RecipientType.BCC, bcc);
}
message.setSubject(subject, CHART_SET_UTF8);
// 最外层部分
MimeMultipart wrapPart = new MimeMultipart("mixed");
MimeMultipart htmlWithImageMultipart = new MimeMultipart("related");
// 文本部分
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(content, CONTENT_TYPE_HTML);
htmlWithImageMultipart.addBodyPart(htmlPart);
// 内嵌图片部分
addImages(images, htmlWithImageMultipart);
MimeBodyPart htmlWithImageBodyPart = new MimeBodyPart();
htmlWithImageBodyPart.setContent(htmlWithImageMultipart);
wrapPart.addBodyPart(htmlWithImageBodyPart);
// 附件部分
addAttachments(attachments, wrapPart);
message.setContent(wrapPart);
Transport.send(message);
return true;
} catch (Exception e) {
log.error("sendByLoadBalance error!", e.getMessage(),
"loadBalanceKey={}, properties={}, to={}, cc={}, "
+ "bcc={}, subject={}, content={}, images={}, attachments={}",
key, properties, to, cc,
bcc, subject, content, images, attachments, e);
}
return false;
}
@Override
public boolean send(Message msg) {
boolean isOk = true;
Transport transport = null;
try {
LOG.info(String.format("Address: %s", msg.getAddress()));
LOG.info(String.format("Subject: %s", msg.getSubject() + ENV));
LOG.info(String.format("Contents: %s", msg.getContents()));
LOG.info(String.format("Host: %s", msg.getHost()));
LOG.info(String.format("Port: %s", msg.getPort()));
LOG.info(String.format("User name: %s", msg.getUserName()));
Properties props = new Properties();
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.host", msg.getHost());
Session session = Session.getInstance(props);
// session.setDebug(true);
MimeMessage message = new MimeMessage(session);
message.setFrom(msg.getFromAddress());
message.setRecipients(javax.mail.Message.RecipientType.TO, msg.getAddress());
message.setSubject(msg.getSubject());
MimeMultipart mmp = new MimeMultipart();
MimeBodyPart mbp = new MimeBodyPart();
mbp.setContent(msg.getContents(), "text/html;charset=UTF-8");
mmp.addBodyPart(mbp);
mmp.setSubType("mixed");
message.setContent(mmp);
message.setSentDate(new Date());
transport = session.getTransport();
transport.connect(msg.getHost(), msg.getPort(), msg.getUserName(), msg.getPassword());
transport.sendMessage(message, message.getAllRecipients());
LOG.error("mail for customize send email success.");
} catch (Exception e) {
isOk = false;
LOG.error("mail for customize send email fail.", e);
} finally {
close(transport);
}
return isOk;
}
/**
* Write and send an email.
*
* @param subject email subject
* @param html the exact html to send out via email
* @param mailHost email host
* @param emailTo email to address
* @param emailCc email cc addresses
* @param emailFrom email from address
* @throws Exception if email fails to send
*/
public static void write(
String subject,
String html,
String mailHost,
String[] emailTo,
String[] emailCc,
String emailFrom)
throws Exception {
InternetAddress[] to = new InternetAddress[emailTo.length];
for (int i = 0; i < emailTo.length && i < to.length; i++) {
to[i] = new InternetAddress(emailTo[i]);
}
InternetAddress[] cc = null;
if (emailCc != null) {
cc = new InternetAddress[emailCc.length];
for (int i = 0; i < emailCc.length && i < cc.length; i++) {
cc[i] = new InternetAddress(emailCc[i]);
}
}
// Sender's email ID needs to be mentioned
InternetAddress from = new InternetAddress(emailFrom);
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty(MAIL_SMTP_HOST, mailHost);
// Get the Session object.
Session session = Session.getInstance(properties);
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// INodeSet From: header field of the header.
message.setFrom(from);
// INodeSet To: header field of the header.
message.addRecipients(Message.RecipientType.TO, to);
if (cc != null && cc.length != 0) {
message.addRecipients(Message.RecipientType.CC, cc);
}
// INodeSet Subject: header field
message.setSubject(subject);
// Send the actual HTML message, as big as you like
MimeBodyPart bodyHtml = new MimeBodyPart();
bodyHtml.setContent(html, MAIL_CONTENT_TEXT_HTML);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(bodyHtml);
message.setContent(multipart);
// Send message
Transport.send(message);
}