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");
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.
Error 1:
Description Resource Path Location Type The project was not built
since its build path is incomplete. Cannot find the class file for
java.util.Map$Entry. Fix the build path then try building this project
EmailSendingWebApp Unknown Java Problem
error 2 :
Description Resource Path Location Type The type java.util.Map$Entry
cannot be resolved. It is indirectly referenced from required .class
files EmailUtility.java /EmailSendingWebApp/src/net/codejava/email
line 29 Java Problem
This is my code:
code 1 : package net.codejava.email;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
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.MimeMessage;
/**
* A utility class for sending e-mail messages
* #author www.codejava.net
*
*/
public class EmailUtility {
public static void sendEmail(String host, String port,
final String userName, final String password, String toAddress,
String subject, String message) 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");
// 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());
msg.setText(message);
// sends the e-mail
Transport.send(msg);
}
}
code 2 :
package net.codejava.email;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* A servlet that takes message details from user and send it as a new e-mail
* through an SMTP server.
*
* #author www.codejava.net
*
*/
#WebServlet("/EmailSendingServlet")
public class EmailSendingServlet extends HttpServlet {
private String host;
private String port;
private String user;
private String pass;
public void init() {
// reads SMTP server setting from web.xml file
ServletContext context = getServletContext();
host = context.getInitParameter("host");
port = context.getInitParameter("port");
user = context.getInitParameter("user");
pass = context.getInitParameter("pass");
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// reads form fields
String recipient = request.getParameter("recipient");
String subject = request.getParameter("subject");
String content = request.getParameter("content");
String resultMessage = "";
try {
EmailUtility.sendEmail(host, port, user, pass, recipient, subject,
content);
resultMessage = "The e-mail was sent successfully";
} catch (Exception ex) {
ex.printStackTrace();
resultMessage = "There were an error: " + ex.getMessage();
} finally {
request.setAttribute("Message", resultMessage);
getServletContext().getRequestDispatcher("/Result.jsp").forward(
request, response);
}
}
}
I am new to eclipse so I don't know how to link these two files, please help. Thanks.
Eclipse can compile Java projects against different installed JREs. Unless care is taken, the project's reference to its JRE is not portable. Verify that your Installed JREs preference page is pointing to something valid, then edit the project's Java Build Path so that it's referring to a valid JRE.
http://help.eclipse.org/neon/topic/org.eclipse.jdt.doc.user/reference/preferences/java/debug/ref-installed_jres.htm
http://help.eclipse.org/neon/topic/org.eclipse.jdt.doc.user/reference/ref-properties-build-path.htm?cp=1_4_3_1
i'm getting some problems with the "session" object while trying to send an Email, that's the code
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
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 EmailSender {
private String user;
private String password;
private String host;
private String destinatario;
private String oggetto;
private String allegato;
/**
*
* Costruttore completo, richiede i parametri
* di connessione al server di posta
* #param user
* #param password
* #param host
* #param mittente
* #param destinatari
* #param oggetto
* #param allegati
*/
public EmailSender(String user, String password, String host,
String destinatario,
String oggetto){
this.user = user;
this.password = password;
this.host = host;
this.destinatario = destinatario;
this.oggetto = oggetto;
}
// Metodo che si occupa dell'invio effettivo della mail
public void inviaEmail() {
int port = 465; //porta 25 per non usare SSL
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.user", user);
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
// commentare la riga seguente per non usare SSL
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.socketFactory.port", port);
// commentare la riga seguente per non usare SSL
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
Session session = Session.getInstance(props, null);
session.setDebug(true);
// Creazione delle BodyParts del messaggio
MimeBodyPart messageBodyPart1 = new MimeBodyPart();
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
try{
// COSTRUZIONE DEL MESSAGGIO
Multipart multipart = new MimeMultipart();
MimeMessage msg = new MimeMessage(session);
// header del messaggio
msg.setSubject(oggetto);
msg.setSentDate(new Date());
msg.setFrom(new InternetAddress(user));
// destinatario
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(destinatario));
// corpo del messaggio
messageBodyPart1.setText("Ciao sono veramente euforico");
multipart.addBodyPart(messageBodyPart1);
// allegato al messaggio
allegato = CreazioneFile.AggiungiDati();
DataSource source = new FileDataSource(allegato);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(allegato);
multipart.addBodyPart(messageBodyPart2);
// inserimento delle parti nel messaggio
msg.setContent(multipart);
Transport transport = session.getTransport("smtps"); //("smtp") per non usare SSL
transport.connect(host, user, password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
System.out.println("Invio dell'email Terminato");
}catch(AddressException ae) {
ae.printStackTrace();
}catch(NoSuchProviderException nspe){
nspe.printStackTrace();
}catch(MessagingException me){
me.printStackTrace();
}
}
}
An that's the Test Class:
import java.io.File;
public class TestEmail {
public static void main(String[] args) {
File allegato = new File(CreazioneFile.AggiungiDati());
EmailSender email = new EmailSender(
"myuser",
"mypass",
"smtp.gmail.com",
"sendToAddress",
"Invio automatico email da Java"
);
email.inviaEmail();
System.out.println(allegato);
allegato.delete();
}
}
That's the stack error:
Exception in thread "main" java.lang.NoClassDefFoundError: com.sun.mail.util.MailLogger
at javax.mail.Session.initLogger(Session.java:226)
at javax.mail.Session.(Session.java:210)
at javax.mail.Session.getDefaultInstance(Session.java:321)
The problem it's for sure about RAD and session,but i dont know where i've to set, and what i've to set, can u please help me?
com.sun.mail.util.MailLogger is part of JavaMail API. It is already included in EE environment (that's why you can use it on your live server), but it is not included in SE environment.
The JavaMail API is available as an optional package for use with Java SE platform and is also included in the Java EE platform.
99% that you run your tests in SE environment which means what you have to bother about adding it manually to your classpath when running tests.
Hope below link will helpful for you
http://crunchify.com/java-mailapi-example-send-an-email-via-gmail-smtp/
In this example Im trying to send an attachment via mail using gmail smtp server.
Mailer.java
package com.servlet.mail;
import java.io.File;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
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.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;
public class Mailer {
public static void send(String to ,String subject ,String msg)
{
System.out.println("in Mailer class");
final String user="sup.ni#gmail.com";
final String psw="XXXXXX";//changes to be made accoordingly
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,psw);
}
});
try
{
System.out.println(to+""+subject+""+msg);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
//message.setText(msg);
//Mail sending with attachement
BodyPart msgBodyPart1 = new MimeBodyPart();
msgBodyPart1.setText("This is message body");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(msgBodyPart1);
MimeBodyPart msgBodyPart2 = new MimeBodyPart();
String path = "D:/Self_Learning/Servlets/Servlet_Examples/WebContent/CSS/";
String filename= path+"Note.txt";
System.out.println(path);
message.setHeader("Content-Disposition", "attachement ; filename= \""+filename+"\"");
DataSource src = new FileDataSource(filename);
msgBodyPart2.setDataHandler(new DataHandler(src));
msgBodyPart2.setFileName(path);
multipart.addBodyPart(msgBodyPart2);
message.setContent(multipart);
//SEND MSG
Transport.send(message);
System.out.println("Mail sent successfully");
}
catch(MessagingException e)
{
System.out.println(e);
}
}
}
The requirement is that I want the attachment name to be just the file name.
Here in this example when I check the mail the attachment will have absolute path.
This is the file-name I receive in the attached file "D:/Self_Learning/Servlets/Servlet_Examples/WebContent/CSS/Note.txt"
But I want the attached file to be just Note.txt
Please let me know what is changes has to be done in order to get my required output
You're setting the filename in the header using the filename= \".....\" key-value pair. Just change this value to the name you want to set.
For example:
String path = "D:/Self_Learning/Servlets/Servlet_Examples/WebContent/CSS/";
String name = "Note.txt";
String filename= path+name;
message.setHeader("Content-Disposition", "attachement ; filename= \""+name+"\"");
I am sending mails from my application using JAVA mail on smtp server, port 465. My need is that, I have to set Message-ID before sending mail. I did some R&D and found the code below. I had override the method updateMessageID() of MimeMessage
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
public class CustomMimeMessage extends MimeMessage {
public CustomMimeMessage(Session session) {
super(session);
}
#Override
protected void updateMessageID() throws MessagingException {
setHeader("Message-ID", "message id");
}
}
And then I had made an instance of CustomMimeMessage in my service and then invoke updateMessageID() method using that instance, but I still get the Message-ID generated by gmail.
In your code
setHeader("Message-ID", "message id");
you are trying to set "message id" as Message-ID which is quite wrong you have to set a unique id that qualify all the rules of the message id (Read This).
Try this..,.
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class CustomMimeMessage extends MimeMessage {
Session session;
private static int id = 0;
public CustomMimeMessage(Session session) {
super(session);
this.session=session;
}
#Override
protected void updateMessageID() throws MessagingException {
setHeader("Message-ID", "<" + getUniqueMessageIDValue(session) + ">");
}
public static String getUniqueMessageIDValue(Session ssn) {
String suffix = null;
InternetAddress addr = InternetAddress.getLocalAddress(ssn);
if (addr != null)
suffix = addr.getAddress();
else {
suffix = "javamailuser#localhost"; // worst-case default
}
StringBuffer s = new StringBuffer();
// Unique string is <hashcode>.<id>.<currentTime>.JavaMail.<suffix>
s.append(s.hashCode()).append('.').append(getUniqueId()).append('.').
append(System.currentTimeMillis()).append('.').
append("JavaMail.").
append(suffix);
return s.toString();
}
private static synchronized int getUniqueId() {
return id++;
}
}
I am doing something similar but sending from the local host instead. This Might help.
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.mail.Transport;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
public class SendEmail {
/**
* Sends an email based on paramaters passed to it.
*
* #param toWho - the recipiants email address
* #param fromWho - the senders email address
* #param subject - the subject line of the email
* #param body - the email message body
* #return void
* #throws AddressException
* #throws MessageingException
*/
public void sendMail(String toWho, String subject, String body, String fromWho) throws AddressException, MessagingException {
// Setting Properties
Properties props = System.getProperties();
props.put("mail.imaps.ssl.trust", "*"); // trusting all server certificates
props.setProperty("mail.store.protocol", "imaps");
// Get the default Session object.
Session session = Session.getDefaultInstance(props, null);
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From header
message.setFrom(new InternetAddress(fromWho));
// Set to header
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toWho));
// Header set subject
message.setSubject(subject);
// Message Body
message.setContent(body, "text/html; charset=utf-8");
// Send message
Transport.send(message);
}
}
You can set message-id to MimeMessage before call Transport.send() by extending MimeMessage like this.
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
public class MyMimeMessage extends MimeMessage {
public MailorMimeMessage(Session session) {
super(session);
}
#Override
protected void updateMessageID() throws MessagingException {
if (getHeader("Message-Id") == null) {
super.updateMessageID();
}
}
}
And set custom message-id.
message.setHeader("Message-Id","<MY-MESSAGE-ID>");
You can try custom id with .(dot) before left side of '#'. It worked for me.
Check the following code snippet:
public class CustomMimeMessage extends MimeMessage {
Session session;
private static int id = 0;
public CustomMimeMessage(Session session) {
super(session);
this.session = session;
}
protected void updateMessageID() throws MessagingException {
debugLog("Calling updateMessageID()");
setHeader("Message-ID", "<" + getUniqueMessageIDValue(session) + ">");
}
public static String getUniqueMessageIDValue(Session ssn) {
String suffix = null;
InternetAddress addr = InternetAddress.getLocalAddress(ssn);
if (addr != null) {
testLog("InternetAddress = " + addr.toString());
String address = addr.getAddress();
if (address.contains("#")) {
address = address.substring(address.lastIndexOf("#"), address.length());
suffix = address;
}
}
if (suffix == null) {
suffix = "#mail";// worst-case default
}
testLog("suffix Address = " + suffix);
StringBuffer s = new StringBuffer();
s.append(System.currentTimeMillis()).append("")
.append(getUniqueId()).append(suffix).append(".sm");
testLog("NEW MESSAGE-ID: " + s.toString());
return s.toString();
}
private static synchronized int getUniqueId() {
return id++;
}
For more details, Please refer the following RFC's. These are really helpful for creating syntax for Custom message-id.
RFC 2822
RFC 5322
Hope this would also work for you.