I am working on Oracle MAF app and using Java mail API for sending outlook meeting requests. I can successfully send mail from java command-line, but when trying same using Mobile app, the code doesn't go after where creating "MimeMessage" class object.
MimeMessage message = new MimeMessage(mailSession);
printStackTrace() shows this exception:
06-09 10:54:43.146: D/JVM(16075): [SEVERE - oracle.adfmf.framework -
Utility - invoke] InvocationTargetException Error: ERROR
[oracle.adfmf.framework.exception.AdfException] - Error invoking
method 'sendMail' in 'class beans.UtilBean'
06-09 12:14:07.466: I/System.out(3760): [SEVERE -
oracle.adfmf.framework - adf.mf.internal - logError] Request:
{"classname":"oracle.adfmf.framework.api.Model","method":"processBatchRequests","params":[false,[{"classname":"oracle.adfmf.framework.api.Model","method":"evaluateMethodExpression","params":["#{UtilBean.sendMail}",[{".type":"oracle.adfmf.amx.event.ActionEvent"}],"void",["oracle.adfmf.amx.event.ActionEvent"]]}]]}
exception: {"message":"Error invoking method 'sendMail' in 'class
beans.UtilBean'",".exception":true,"severity":"ERROR",".type":"oracle.adfmf.framework.exception.AdfException"}
Full source code of my class is here:
package beans;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import oracle.adfmf.amx.event.ActionEvent;
public class Email {
private static final String SMTP_HOST_NAME = "mail_host_name";
private static final String SMTP_AUTH_USER = "smtp_user_id";
private static final String SMTP_AUTH_PWD = "smtp_auth_pass";
private static final String SMTP_AUTH_PORT = "smtp_port";
private static final String MAIL_FROM_ADDRESS = "from_addr";
private static final String RECEIPENT_1 = "receipent_1_addr";
private static final String RECEIPENT_2 = "receipent_2_addr";
public void sendEmail(ActionEvent actionEvent) {
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", SMTP_AUTH_PORT);
Authenticator auth = new SMTPAuthenticator();
//Get the session object
Session mailSession = Session.getDefaultInstance(props, auth);
//compose message
try {
System.out.print("CALLED0"); //I can see this in Logcat Logs
MimeMessage message = new MimeMessage(mailSession); // Program stuck here
System.out.print("CALLED1");//I can not see this in Logcat Logs
message.addHeaderLine("method=REQUEST");
message.addHeaderLine("charset=UTF-8");
message.addHeaderLine("component=vevent");
message.setFrom(new InternetAddress(MAIL_FROM_ADDRESS));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(RECEIPENT_1));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(RECEIPENT_2));
message.setSubject("Outlook Meeting Request Using JavaMail");
StringBuffer sb = new StringBuffer();
StringBuffer buffer =
sb.append("BEGIN:VCALENDAR\n" + "PRODID:-//Microsoft Corporation//Outlook 10.0 MIMEDIR//EN\n" +
"VERSION:2.0\n" + "METHOD:REQUEST\n" + "BEGIN:VEVENT\n" +
"ATTENDEE;CN=\"Attendee1\";ROLE=REQ-PARTICIPANT;MAILTO:attendee1#addendant.com\n" +
"ATTENDEE;CN=\"Attendee2\";ROLE=OPT-PARTICIPANT;MAILTO:attendee2#addendant.com\n" +
"ORGANIZER:MAILTO:org#org.com\n" + "DTSTART:20050406T073000Z\n" +
"DTEND:20050406T080000Z\n" + "LOCATION:conf\n" + "TRANSP:OPAQUE\n" + "SEQUENCE:0\n" +
"UID:040000008200E00074C5B7101A82E00800000000A0A742E5073AC5010000000000000000100\n" +
" 0000029606C073D82204AB6C77ACE6BC2FBE2\n" + "DTSTAMP:20050405T122004Z\n" +
"CATEGORIES:Meeting\n" + "DESCRIPTION:What are you doing?\n\n" + "SUMMARY:How are you?\n" +
"PRIORITY:5\n" + "CLASS:PUBLIC\n" + "BEGIN:VALARM\n" + "TRIGGER:PT1440M\n" +
"ACTION:DISPLAY\n" + "DESCRIPTION:Reminder\n" + "END:VALARM\n" + "END:VEVENT\n" +
"END:VCALENDAR\n");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setHeader("Content-Class", "urn:content-classes:calendarmessage");
messageBodyPart.setHeader("Content-ID", "calendar_message");
messageBodyPart.setContent(buffer.toString(), "text/calendar");
// Create a Multipart
Multipart multipart = new MimeMultipart();
// Add part one
multipart.addBodyPart(messageBodyPart);
// Put parts in message
message.setContent(multipart);
//send message
Transport.send(message);
System.out.println("message sent successfully");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
String username = SMTP_AUTH_USER;
String password = SMTP_AUTH_PWD;
return new PasswordAuthentication(username, password);
}
}
}
In Email class I added print statement before and after where creating "MimeMessage" class object, I am able to see first print in logcat but not second.
Deploying java project on Web logic server as a web service (as a .war package) worked for me.
Related
Hi I am trying to use java to download attachment's from the mail which is received on the current date.
But while checking for IMAP or POP3 server details to connect it shown as not available. Can any one tell me how to overcome this issue is there any other way to connect?
I was some what able to connect but now i am getting below error
OK The Microsoft Exchange IMAP4 service is ready. [KJGHFUFJHGKLJYOYRGFJHGFYFTHGFJYTFYJTFAwADEAQwBBADAAMAA1ADIALgBJAE4ARABQAFIARAAwADEALgBQAFIATwBEAC4ATwBVAFQATABPAE8ASwAuAEMATwBNAA==]
B0 CAPABILITY
CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS ID UNSELECT CHILDREN IDLE NAMESPACE LITERAL+
B0 OK CAPABILITY completed.
DEBUG IMAP: AUTH: PLAIN
DEBUG IMAP: AUTH: XOAUTH2
DEBUG IMAP: protocolConnect login, host=outlook.office365.com, user=name#outlook.com, password= non-null
DEBUG IMAP: AUTHENTICATE PLAIN command trace suppressed
DEBUG IMAP: AUTHENTICATE PLAIN command result: B1 NO AUTHENTICATE failed.
Exception in thread "main" javax.mail.AuthenticationFailedException: AUTHENTICATE failed.
Below is the code I used
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.internet.MimeBodyPart;
import javax.mail.search.FlagTerm;
import com.j256.simplemagic.ContentInfo;
import com.j256.simplemagic.ContentInfoUtil;
import com.j256.simplemagic.ContentType;
import org.apache.commons.codec.binary.Base64;
public class test2 {
public static void main(String[]args)throws Exception {
Properties props = System.getProperties();
//String imapProtocol = System.getgetImapSsl() != null && server.getImapSsl() == true ? "imaps" : "imap";
props.setProperty("mail.store.protocol", "imap");
props.setProperty("mail.imap.ssl.enable", "true");
props.setProperty("mail.imaps.partialfetch", "false");
props.put("mail.mime.base64.ignoreerrors", "true");
//props.put("mail.imap.auth", "true");
Session mailSession = Session.getDefaultInstance(props
,
new javax.mail.Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("NAME#OUTLOOK.com", "PASSWORD");// Specify the Username and the PassWord
}
});
String test = "Workwork112233!";
System.out.println(test);
mailSession.setDebug(true);
Store store = mailSession.getStore("imap");
store.connect( "outlook.office365.com","NAME#OUTLOOK.com", "PASSWORD");
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
System.out.println("Total Message:" + folder.getMessageCount());
System.out.println("Unread Message:" + folder.getUnreadMessageCount());
Message[] messages = folder.getMessages();
for (Message mail : messages) {
if (!mail.isSet(Flags.Flag.SEEN)) {
System.out.println("***************************************************");
System.out.println("MESSAGE : \n");
System.out.println("Subject: " + mail.getSubject());
System.out.println("From: " + mail.getFrom()[0]);
System.out.println("To: " + mail.getAllRecipients()[0]);
System.out.println("Date: " + mail.getReceivedDate());
System.out.println("Size: " + mail.getSize());
System.out.println("Flags: " + mail.getFlags());
System.out.println("ContentType: " + mail.getContentType());
System.out.println("Body: \n" + getEmailBody(mail));
// System.out.println("Has Attachments: " + hasAttachments(mail));
}
}
}
public static String getEmailBody(Message email) throws IOException, MessagingException {
String line, emailContentEncoded;
StringBuffer bufferEmailContentEncoded = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(email.getInputStream()));
while ((line = reader.readLine()) != null) {
bufferEmailContentEncoded.append(line);
}
System.out.println("**************************************************");
System.out.println(bufferEmailContentEncoded);
System.out.println("**************************************************");
emailContentEncoded = bufferEmailContentEncoded.toString();
if (email.getContentType().toLowerCase().contains("multipart/related")) {
emailContentEncoded = emailContentEncoded.substring(emailContentEncoded.indexOf("base64") + 6);
emailContentEncoded = emailContentEncoded.substring(0, emailContentEncoded.indexOf("Content-Type") - 1);
System.out.println(emailContentEncoded);
String emailContentDecoded = new String(new Base64().decode(emailContentEncoded.toString().getBytes()));
return emailContentDecoded;
}
return emailContentEncoded;
}}
Following code sample found in:
https://www.codejava.net/java-ee/javamail/embedding-images-into-e-mail-with-javamail
The images are attached to the email, but not embedded in the html of the email.
package net.codejava.mail;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
/**
* This utility class provides a functionality to send an HTML e-mail message
* with embedded images.
* #author www.codejava.net
*
*/
public class EmbeddedImageEmailUtil {
/**
* Sends an HTML e-mail with inline images.
* #param host SMTP host
* #param port SMTP port
* #param userName e-mail address of the sender's account
* #param password password of the sender's account
* #param toAddress e-mail address of the recipient
* #param subject e-mail subject
* #param htmlBody e-mail content with HTML tags
* #param mapInlineImages
* key: Content-ID
* value: path of the image file
* #throws AddressException
* #throws MessagingException
*/
public static void send(String host, String port,
final String userName, final String password, String toAddress,
String subject, String htmlBody,
Map<String, String> mapInlineImages)
throws AddressException, MessagingException {
// sets SMTP server properties
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.user", userName);
properties.put("mail.password", password);
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(htmlBody, "text/html");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// adds inline image attachments
if (mapInlineImages != null && mapInlineImages.size() > 0) {
Set<String> setImageID = mapInlineImages.keySet();
for (String contentId : setImageID) {
MimeBodyPart imagePart = new MimeBodyPart();
imagePart.setHeader("Content-ID", "<" + contentId + ">");
imagePart.setDisposition(MimeBodyPart.INLINE);
String imageFilePath = mapInlineImages.get(contentId);
try {
imagePart.attachFile(imageFilePath);
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(imagePart);
}
}
msg.setContent(multipart);
Transport.send(msg);
}
}
package net.codejava.mail;
import java.util.HashMap;
import java.util.Map;
/**
* This program tests out the EmbeddedImageEmailUtil utility class.
* #author www.codejava.net
*
*/
public class InlineImageEmailTester {
/**
* main entry of the program
*/
public static void main(String[] args) {
// SMTP info
String host = "smtp.gmail.com";
String port = "587";
String mailFrom = "YOUR_EMAIL";
String password = "YOUR_PASSWORD";
// message info
String mailTo = "YOUR_RECIPIENT";
String subject = "Test e-mail with inline images";
StringBuffer body
= new StringBuffer("<html>This message contains two inline images.<br>");
body.append("The first image is a chart:<br>");
body.append("<img src=\"cid:image1\" width=\"30%\" height=\"30%\" /><br>");
body.append("The second one is a cube:<br>");
body.append("<img src=\"cid:image2\" width=\"15%\" height=\"15%\" /><br>");
body.append("End of message.");
body.append("</html>");
// inline images
Map<String, String> inlineImages = new HashMap<String, String>();
inlineImages.put("image1", "E:/Test/chart.png");
inlineImages.put("image2", "E:/Test/cube.jpg");
try {
EmbeddedImageEmailUtil.send(host, port, mailFrom, password, mailTo,
subject, body.toString(), inlineImages);
System.out.println("Email sent.");
} catch (Exception ex) {
System.out.println("Could not send email.");
ex.printStackTrace();
}
}
}
Any comments will be very appreciated.
Problem solved.
I have to change:
new MimeMultipart();
to this:
new MimeMultipart("related");
I created a method to send email in VB.NET:
Imports System.Threading
Imports System.Net.Mail
Imports System.ComponentModel
Module Module1
Dim smtpList As New ArrayList
Dim counter = 0
Private Sub smtpClient_SendCompleted(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs)
System.Diagnostics.Debug.WriteLine("completed!")
System.Console.WriteLine("completed!")
End Sub
Public Function createSmtp() As SmtpClient
Dim smtp = New SmtpClient()
Dim user = "AKAKAKAKAKAKAKAK"
Dim host = "smtp.mailgun.org"
Dim pass = "akakakakakakakakakakakakakakakakakakakak"
smtp.Host = host
smtp.Port = 587
smtp.Credentials = New System.Net.NetworkCredential(user, pass)
smtp.EnableSsl = True
Return smtp
End Function
Public Sub SendEmail(email As String, bodystuff As String, smtp As SmtpClient)
Dim from As New MailAddress("contat#testsitetetete.com", "Info", System.Text.Encoding.UTF8)
Dim [to] As New MailAddress(email)
Dim message As New MailMessage(from, [to])
message.Body = String.Format("The message I want to send is to this <b>contact: {0}{1}</b>", vbCrLf, bodystuff)
message.IsBodyHtml = True
message.BodyEncoding = System.Text.Encoding.UTF8
message.Subject = "Test email subject"
message.SubjectEncoding = System.Text.Encoding.UTF8
message.Priority = MailPriority.High
' Set the method that is called back when the send operation ends.
AddHandler smtp.SendCompleted, AddressOf smtpClient_SendCompleted
smtp.Send(message)
'smtp.SendMailAsync(message)
counter = counter + 1 ' I know its not thread safe, just to get a counter
System.Console.WriteLine("Counter -> " & counter)
End Sub
Public Sub StartEmailRun()
System.Diagnostics.Debug.WriteLine("StartEmailRun")
'Dim smtp = createSmtp()
Try
For i = 0 To 8
Dim thread As New Thread(
Sub()
Dim smtp = createSmtp()
SendEmail("someamail#testemail.com", "email test", createSmtp())
End Sub
)
thread.Start()
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Sub Main()
System.Diagnostics.Debug.WriteLine("Starting the email sending...")
ThreadPool.SetMinThreads(100, 100) ' just to make sure no thread pool issue or limitation
createSmtp()
StartEmailRun()
Thread.Sleep(300000) ' make the program alive
End Sub
End Module
and I created this same method in java:
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class TestMail
{
public static void main(String[] args) throws AddressException, MessagingException, InterruptedException
{
Properties prop = new Properties();
prop.put("mail.smtp.auth", true);
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.smtp.host", "smtp.mailgun.org");
prop.put("mail.smtp.port", "587");
prop.put("mail.smtp.ssl.trust", "smtp.mailgun.org");
Session session = Session.getInstance(prop, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
String username = "akakakakakakakakakak";
String password = "kajdfkjasfkjasdfksjdfksdajfksdfjsdkfjdskfjkW";
return new PasswordAuthentication(username, password);
}
});
final Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("testacount#test.com"));
message.setRecipients(
Message.RecipientType.TO, InternetAddress.parse("atest#test.com"));
message.setSubject("Mail Subject");
String msg = "This is my first email using JavaMailer";
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(msg, "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);
message.setContent(multipart);
for (int i = 0; i < 8; i++)
{
new Thread(new Runnable() {
public void run() {
try {
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
System.out.println("sent...");
}
}).start();
}
while(true)
{
Thread.sleep(1000);
}
}
}
I expected the VB.NET code to sent the emails simultanteously, like the java one does.
But the email sent appears to be sequencial. In the java all the emails are sent simultaneosly.
I think there is some limitation on send multiple emails in the VB.Net code.
Is there a way to send multiple emails at the same time in VB.NET???
p.s. not talking about bbc, because every email is different from another.
I am sending mail in with a excel attachment file through JAVA mail. Whenever i send the email to a IMAP email box it's filename gets changed to Untitled attachment as oppose to name i am passing for other email boxes it works file.
I have contacted my email provided and they suspect it is formatting issue as JAVa mail by default formats in RFC 2231, for IMAP it has to be RFC 2047/2231.
Note: application is deployed on Widfly 9 using JAVA 8.
This is how i call the method:
ByteArrayOutputStream baos = new ByteArrayOutputStream(excel_bytes.length);
baos.write(excel_bytes, 0, excel_bytes.length);
DataSource aAttachment = new ByteArrayDataSource(baos.toByteArray(),"application/vnd.ms-excel");
String to_email = tenant.getEmail();
email.sendRechargeBillEmail(to_email, aAttachment, file_name + ".xlsx",tenant.getCompanyName(), String.valueOf(job.getStartDate()), String.valueOf(job.getEndDate()));
This is the class which does have the email methods:
package com.nextcontrols.rechargecalculation;
import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import java.util.logging.Logger;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
public class SendAttachmentInEmail {
private static final Logger logger =
Logger.getLogger(SendAttachmentInEmail.class.getCanonicalName());
public void sendEmail(String to_email, DataSource attachment, String
file_name, String from_email, String user_name, String password, String
email_body, String email_subject) {
Properties props = new Properties();
props.put("mail.smtp.host", "mail2.nextcontrols.local");
Session session = Session.getDefaultInstance(props);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from_email));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to_email));
message.setSubject(email_subject);
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(email_body, "text/html; charset=utf-8");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
MimeBodyPart mailattachment = new MimeBodyPart();
DataSource source = attachment;
mailattachment.setFileName(file_name);
mailattachment.setDataHandler(new DataHandler(source));
mailattachment.setDisposition(MimeBodyPart.ATTACHMENT);
multipart.addBodyPart(mailattachment);
message.setContent(multipart);
Transport.send(message);
logger.info("////// Sent message successfully to "+ to_email);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
public void sendRechargeBillEmail(String to_email, DataSource attachment, String file_name,String tenant_name, String start_date, String end_date){
String subject = "Billing - " + tenant_name + " - " + start_date + " to " + end_date;
String bodyText = "Please find attached your utility recharge bill for " + start_date + " to " + end_date;
String note = "<i>This is an automated email, please do not reply to this address</i>";
String fromText = "Regards,<br />-- <br />";
String disclaimerTop = "Privacy and Confidentiality Notice";
String disclaimerDown = " txt";
bodyText = bodyText + "<br /> <br /> <br />" + note + "<br />" + fromText + "<br />" + addColor (disclaimerTop, Color.GRAY ,"2") + "<br />" + addColor(disclaimerDown, Color.GRAY, "1");
sendEmail(to_email, attachment, file_name, "noreply#nxt.com", "Billing", "billing", bodyText, subject);
}
public static String addColor(String msg, Color color, String size) {
String hexColor = String.format("#%06X", (0xFFFFFF & color.getRGB()));
String colorMsg = "<FONT size = \" "+ size +"\" COLOR=\"" + hexColor + "\">" + msg + "</FONT>";
return colorMsg;
}
}
If your IMAP server is changing the file name because it doesn't understand RFC 2231, then it really needs to be updated. RFC 2231 is 20 years old.
You can disable the use of RFC 2231 to encode the file name by setting the JavaMail System property mail.mime.encodeparameters to "false".
The "loginVo.htmlBody(messageBodyPart);" will contain the html formatted designed information, but in mail does not receive it.
JAVA - STRUTS2
package com.action;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import com.opensymphony.xwork2.Action;
import com.bo.LoginBo;
import com.manager.AttendanceManager;
import com.manager.LoginManager;
import com.manager.SSLEmail;
import com.vo.AttendanceManagementVo;
import com.vo.LeaveManagementVo;
import com.vo.LoginVo;
import com.sun.corba.se.impl.protocol.giopmsgheaders.Message;
import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeBodyPart;
public class InsertApplyLeaveAction implements Action {
private AttendanceManagementVo attendanceManagementVo;
public AttendanceManagementVo getAttendanceManagementVo() {
return attendanceManagementVo;
}
public void setAttendanceManagementVo(
AttendanceManagementVo attendanceManagementVo) {
this.attendanceManagementVo = attendanceManagementVo;
}
#Override
public String execute() throws Exception {
String empId=attendanceManagementVo.getEmpId();
String leaveType=attendanceManagementVo.getLeaveType();
String leaveStartDate=attendanceManagementVo.getLeaveStartDate();
String leaveEndDate=attendanceManagementVo.getLeaveEndDate();
String reason=attendanceManagementVo.getReason();
String employeeName=attendanceManagementVo.getEmployeeName();
String manageEmployeeId=empId;
float totalLeave=attendanceManagementVo.getTotalLeave();
String leaveStatus=attendanceManagementVo.getLeaveStatus();
// String approverId=attendanceManagementVo.getApproverId();
attendanceManagementVo.setEmpId(empId);
attendanceManagementVo.setLeaveType(leaveType);
attendanceManagementVo.setLeaveStartDate(leaveStartDate);
attendanceManagementVo.setLeaveEndDate(leaveEndDate);
attendanceManagementVo.setReason(reason);
attendanceManagementVo.setManageEmployeeId(manageEmployeeId);
attendanceManagementVo.setTotalLeave(totalLeave);
attendanceManagementVo.setLeaveStatus(leaveStatus);
attendanceManagementVo.setEmployeeName(employeeName);
AttendanceManagementVo attendanceManagementVo1=new AttendanceManagementVo();
AttendanceManager attendanceManager=new AttendanceManager();
attendanceManagementVo1=attendanceManager.insertLeaveData(attendanceManagementVo);
attendanceManagementVo1=attendanceManager.getApproverId(attendanceManagementVo);
String approverId=attendanceManagementVo1.getApproverId();
String approverEmployeeName=attendanceManagementVo1.getApproverEmployeeName();
LoginVo loginVo=new LoginVo();
LoginManager loginManager=new LoginManager();
loginVo.setEmpId(approverId);
loginVo=loginManager.getEmailAddress(loginVo);
String emailAddress=loginVo.getEmailAddress();
String subject="LEAVE IS SUBMITTED FOR AN APPROVAL BY THE - " +employeeName;
// String body = "Hi "+approverEmployeeName+" ," + "\n" + "\n" +
// leaveType+" is Applied for "+totalLeave+" days by the " +employeeName+ "\n" + "\n" +
// " Employee Name: " + employeeName +"\n" +
// " Applied Leave Type: " + leaveType +"\n" +
// " Total Days: " + totalLeave +"\n" + "\n" +
// " To view Leave History, Please visit the employee poratal or copy and paste the below link in your browser: " + "\n" +
// " NOTE : This is an automated message. Please do not reply."+ "\n" + "\n" +
Session session = Session.getInstance(null, null);
MimeBodyPart messageBodyPart = new MimeBodyPart();
MimeMessage message = new MimeMessage(session);
Multipart multipart = new MimeMultipart();
String htmlText = ("<div style=\"color:red;\">BRIDGEYE</div>");
messageBodyPart.setContent(htmlText, "text/html");
loginVo.setHtmlBody(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
loginVo.setSubject(subject);
// loginVo.setBody(body);
loginVo.setEmailAddress(emailAddress);
SSLEmail sSSEmail=new SSLEmail();
sSSEmail.sendEmail(loginVo);
return "success";
}
}
If we comment that "loginVo.setHtmlBody(messageBodyPart);" part from coding and uncomment the "String body" means email is sending properly with a plain text.
By using the Above code as like it means it showing the
Struts has detected an unhandled exception: Messages: File: javax/mail/Session.java Line number: 206 "ABOVE IS A ERROR SHOWING WHILE RUNNING THE CODE"
To send your message as HTML you should do something
messageBodyPart = new MimeBodyPart();
String htmlText = body.replaceAll("\n","<br>");
messageBodyPart.setContent(htmlText, "text/html");
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);