I have the below simple code to check for emails after a form has been submitted. Sometimes it takes a while for the email to be sent. I have given a thread.sleep for 20s before the email method call and even that is less. Is there something i can add to the code to wait till an email is received?
public void Checkemail(String imap,String username, String password, String message) throws MessagingException
{
SoftAssert softAssert=new SoftAssert();
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imap");
props.setProperty("mail.imaps.partialfetch", "false");
props.put("mail.imap.ssl.enable", "true");
props.put("mail.mime.base64.ignoreerrors", "true");
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imap");
store.connect(imap, 993, username, password);
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
System.out.println("Total Messages:" + folder.getMessageCount());
System.out.println("Unread Messages:" + folder.getUnreadMessageCount());
Message[] messages = folder.getMessages();
boolean test=false;
if(folder.getUnreadMessageCount()!=0)
{
for (Message mail : messages)
{
Address[] froms = mail.getFrom();
String email = froms == null ? null : ((InternetAddress) froms[0]).getAddress();
if(!mail.isSet(Flags.Flag.SEEN) && email.contains("abc#abc.com") && mail.getSubject().contains(message))
{
mail.setFlag(Flags.Flag.SEEN, true);
softAssert.assertTrue(true,"Email received ->");
Reporter.log("Email received ->" + mail.getSubject(), true);
test=true;
break;
// folder.setFlags(messages, null, true);
}
}
if (!test)
{
softAssert.assertTrue(false, "Email not received");
Reporter.log("Email not received ->" + message, true);
}
}
else
{
softAssert.assertTrue(false, "Email not received");
Reporter.log("Email not received ->" + message, true);
}
}
Some time ago I was using this to wait for email delivery at mailinator.com:
WebDriverWait wait5m = new WebDriverWait(driver,300);
Boolean new_msg = wait5m.until(new Function<WebDriver, Boolean> () {
public Boolean apply(WebDriver driver) {
List<WebElement> msg = driver.findElements(By.linkText(usr_eml));
driver.navigate().refresh();
try {Thread.sleep(1000);} catch (InterruptedException e) {}
if(msg.size()>0)
{
return true;
}
return false;
}
});
Related
I have this sendmail function that I want to Test in Junit 4 using MockMvc.
I have provided my test case and WiserAssertions.java file I am using to test the function.
When testing the Junit test case I am getting the AssertionError that
java.lang.AssertionError: No message from [demoprojintern#gmail.com] found!
at com.appointment.request.controller.WiserAssertions.lambda$7(WiserAssertions.java:67)
Can someone help me out what am I missing?
sendmail() function
public void sendmail(Request request) throws AddressException, MessagingException, IOException {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
String email = request.getEmail();
int requestId1 = request.getRequestId();
String requestId = Integer.toString(requestId1);
String name = request.getLegalName();
String cause = request.getCause();
String doa = request.getDateOfAppointment();
String toa = request.getAppointmentTime();
int status = request.getRequestStatus();
String generic = "Hello, " + name + "<br><br>" + "Your request with Request ID: " + requestId + " for " + "the cause of "
+ cause + " on " + doa + " at " + toa + " has been ";
String regards = "<br><br><br>Thanks and Regards,<br>";
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("<my-email-id>", "<my-email-id's password");
}
});
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("<my-email-id>", false));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
msg.setSubject("Regarding your Appointment Request");
msg.setContent(" ", "text/html");
msg.setSentDate(new Date());
MimeBodyPart messageBodyPart = new MimeBodyPart();
if (status == 0) {
String messageForPendingRequest = generic + "<strong>RECEIVED</strong>." + regards;
messageBodyPart.setContent(messageForPendingRequest, "text/html");
}
if (status == 1) {
String messageForPendingRequest = generic + "<strong>APPROVED</strong>." + regards;
messageBodyPart.setContent(messageForPendingRequest, "text/html");
}
if (status == 2) {
String messageForPendingRequest = generic + "<strong>SUGGESTED</strong>." + regards;
messageBodyPart.setContent(messageForPendingRequest, "text/html");
}
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
msg.setContent(multipart);
Transport.send(msg);
}
These are the dependencies of my pom.xml for sending the email and testing the mail respectively
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.subethamail</groupId>
<artifactId>subethasmtp</artifactId>
<version>3.1.7</version>
<scope>test</scope>
</dependency>
This is my junit test case
private Wiser wiser;
#Test
public void send() throws Exception {
Request request = new Request(1234, "Richie Rich", "<patient's-email-id>", "Brain", 27, "2019-12-17", "13:00", 0, "", "", "");
String email = request.getEmail();
int requestId1 = request.getRequestId();
String requestId = Integer.toString(requestId1);
String name = request.getLegalName();
String cause = request.getCause();
String doa = request.getDateOfAppointment();
String toa = request.getAppointmentTime();
String generic = "Hello, " + name + "<br><br>" + "Your request with Request ID: "
+ requestId + " for " + "the cause of "
+ cause + " on " + doa + " at " + toa + " has been ";
String regards = "<br><br><br>Thanks and Regards,<br>";
String jsonRequest = objectMapper.writeValueAsString(request);
this.mockMvc.perform(post("/sendemail").content(jsonRequest).contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk());
// assert
WiserAssertions.assertReceivedMessage(wiser)
.from("<sender-mail-id>")
.to(email)
.withSubject("Regarding your Appointment Request")
.withContent(generic + "<strong>RECEIVED</strong>." + regards);
}
This is my WiserAssertions.java that I got from a blog
public class WiserAssertions {
private final List<WiserMessage> messages;
private WiserAssertions(List<WiserMessage> messages) {
this.messages = messages;
}
public static WiserAssertions assertReceivedMessage(Wiser wiser) {
return new WiserAssertions(wiser.getMessages());
}
private static Supplier<AssertionError> assertionError(String errorMessage, String... args) {
return () -> new AssertionError(MessageFormat.format(errorMessage, args));
}
public static <T> T unchecked(ThrowingSupplier<T> supplier) {
try {
return supplier.get();
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
public WiserAssertions from(String from) {
findFirstOrElseThrow(m -> m.getEnvelopeSender().equals(from),
assertionError("No message from [{0}] found!", from));
return this;
}
public WiserAssertions to(String to) {
findFirstOrElseThrow(m -> m.getEnvelopeReceiver().equals(to),
assertionError("No message to [{0}] found!", to));
return this;
}
public WiserAssertions withSubject(String subject) {
Predicate<WiserMessage> predicate = m -> subject.equals(unchecked(getMimeMessage(m)::getSubject));
findFirstOrElseThrow(predicate,
assertionError("No message with subject [{0}] found!", subject));
return this;
}
public WiserAssertions withContent(String content) {
findFirstOrElseThrow(m -> {
ThrowingSupplier<String> contentAsString =
() -> ((String) getMimeMessage(m).getContent()).trim();
return content.equals(unchecked(contentAsString));
}, assertionError("No message with content [{0}] found!", content));
return this;
}
private void findFirstOrElseThrow(Predicate<WiserMessage> predicate, Supplier<AssertionError> exceptionSupplier) {
messages.stream().filter(predicate)
.findFirst().orElseThrow(exceptionSupplier);
}
private MimeMessage getMimeMessage(WiserMessage wiserMessage) {
return unchecked(wiserMessage::getMimeMessage);
}
interface ThrowingSupplier<T> {
T get() throws Throwable;
}
}
I want to get the message number list that the content type is "multipart".I tried using javaxmail, it works but i don't want to get the messages and then do the filter.
try {
Session emailSession = Session.getDefaultInstance(this.setPropertiesParams());
Store store = emailSession.getStore("imaps");
store.connect(host, email, emailPassword);
Folder emailFolder;
emailFolder = store.getFolder("Documents");
emailFolder.open(Folder.READ_ONLY);
SearchTerm andTerm = searchMessageByDate(fromDate, toDate);
Message[] messages = emailFolder.search(andTerm);
Message[] finalMessages = emailFolder.search(new SubjectTerm("Scan de votre document"), messages);
for (Message message : finalMessages) {
String contentType = message.getContentType();
if (contentType.contains("multipart")) {
Integer messageNumber = message.getMessageNumber();
numberList.add(messageNumber);
}
}
emailFolder.close(false);
store.close();
How to do it. thanks for any help.
You can implement a new subclass of SearchTerm that does that, but the message would probably have to be fetched anyway. I don't think you can avoid it.
public class ContentTypeTerm extends SearchTerm {
#Override
public boolean match(Message msg) {
try {
return msg.isMimeType("multipart/*");
} catch (MessagingException ex) {
throw new RuntimeException(ex.getMessage());
}
}
}
UPDATE
You could actually use a HeaderTerm:
SearchTerm[] terms = {
searchMessageByDate(fromDate, toDate),
new HeaderTerm("Content-Type", "multipart/.*")
};
SearchTerm andTerm = new AndTerm(terms);
I know this issue is old, but I didn't find any solution for SimpleMailMessage with properties added in the class and not in the xml. There is no exeption after my app starts, its simply not sending mail. The method CustomMailDeliveryImpl.sendMail() is trigered from Controlller. I cant find a mistake.
#Component("CustomMailDelivery")
public class CustomMailDeliveryImpl implements CustomMailDelivery {
protected static Logger logger = Logger.getLogger(CustomMailDeliveryImpl.class);
private EmployeeService employeeService;
private String username = "* * *#gmail.com";
private String password = "* * *";
private JavaMailSenderImpl sender = new JavaMailSenderImpl();
#Autowired
public void setSender(JavaMailSenderImpl sender) {
this.sender = sender;
}
#Autowired
public void setEmployeeService(EmployeeService employeeService) {
this.employeeService = employeeService;
}
/**
* #param from - must contain address of sender,
* #param to - must contain address of target,
* #param subject - must be included with short description,
* #param body - main message of mail.
* #throws RuntimeException if any param is empty.
*/
public void sendMail(String from, String to, String subject, String body) {
// selecting settings from DB
SystemSettingsModel settingsModel = employeeService.getSettingsByName("default");
// defining settings
sender.setHost(settingsModel.getSmtpServerAddress());
sender.setPort(settingsModel.getSmtpServerPort());
sender.setUsername(username);
sender.setPassword(password);
// defining SMTP properties
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.debug", "1");
Session session = Session.getDefaultInstance(properties, null);
sender.setSession(session);
// initiating mail
SimpleMailMessage simpleMessage = new SimpleMailMessage();
try {
if (from != null && to != null) {
if (subject != null && body != null) {
simpleMessage.setFrom(from);
simpleMessage.setTo(to);
simpleMessage.setSubject(subject);
simpleMessage.setText(body);
sender.send(simpleMessage);
logger.debug("Mail has been sent successfully");
} else {
throw new MessagingException("Subject and message of mail is empty!");
}
} else {
throw new MessagingException("Address of object and target is empty!");
}
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
Any help appreciated !!!!
I finally managed to overcome this issue and I did found the solution! With this way? you can pass properties from page configuration or DAO Service!
#Component("CustomMailDeliveryImpl")
public class CustomMailDeliveryImpl implements CustomMailDelivery {
private EmployeeService employeeService;
private Transport transport;
private String username = "***#gmail.com";
private String password = "***";
private SystemSettingsModel settingsModel;
private Session session;
private MimeMessage message;
private InternetAddress fromAddress, toAddress;
private Properties properties;
#Autowired
public void setEmployeeService(EmployeeService employeeService) {
this.employeeService = employeeService;
}
public void sendMail(String from, String to, String subject, String body) throws SendFailedException {
settingsModel = employeeService.getSettingsByName("default");
// defining properties
properties = new Properties();
properties.put("mail.smtp.host", settingsModel.getSmtpServerAddress());
properties.put("mail.smtp.port", settingsModel.getSmtpServerPort());
properties.put("mail.smtp.user", username);
properties.put("mail.smtp.password", password);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
// InternetAddress initialisation
try {
fromAddress = new InternetAddress(from);
toAddress = new InternetAddress(to);
// new Authenticator session
session = (javax.mail.Session) Session.getDefaultInstance(properties, null);
} catch (AddressException e) {
throw new RuntimeException();
}
// executing mail sending
try {
if (from != null && to != null) {
if (subject != null && body != null) {
// defining message
message = new MimeMessage(session);
message.setFrom(fromAddress);
message.addRecipient(Message.RecipientType.TO, toAddress);
message.setSubject(subject);
message.setText(body);
message.setSentDate(new Date());
message.setHeader("MIME-Version" , "1.0" );
message.setHeader("Content-Type" , "text/html" );
// Transport initialisation
if (transport == null) {
transport = session.getTransport("smtp");
if (!transport.isConnected())
transport.connect(settingsModel.getSmtpServerAddress(),
settingsModel.getSmtpServerPort(), username, password);
}
transport.sendMessage(message, message.getAllRecipients());
} else {
throw new MessagingException("Subject and message of mail is empty!");
}
} else {
throw new MessagingException("Address and target of mail is empty!");
}
} catch (MessagingException e) {
e.printStackTrace();
throw new RuntimeException();
} finally {
if (transport != null) try {
transport.close();
} catch (MessagingException ignore) {
}
}
}
}
It's working just perfect!!
I work with log4j.properties through WSO2 products. I needed implement a appender to work with SMTPAppender and send emails notifications using gmail smtp server. So, when I config log4j and start ESB WSO2 Server, the manage console print: log4j:ERROR Could not instantiate class [com.notification.GmailSMTPAppender].
My implementation was:
package com.notification;
public class GmailSMTPAppender extends SMTPAppender {
protected Session session;
public GmailSMTPAppender() {
super();
}
/**
* Create mail session.
*
* #return mail session, may not be null.
*/
protected Session createSession() {
Properties props = new Properties();
props.put("mail.smtps.host", getSMTPHost());
props.put("mail.smtps.auth", "true");
Authenticator auth = null;
if (getSMTPPassword() != null && getSMTPUsername() != null) {
auth = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(getSMTPUsername(),
getSMTPPassword());
}
};
}
session = Session.getInstance(props, auth);
if (getSMTPProtocol() != null) {
session.setProtocolForAddress("rfc822", getSMTPProtocol());
}
if (getSMTPDebug()) {
session.setDebug(getSMTPDebug());
}
return session;
}
/**
* Send the contents of the cyclic buffer as an e-mail message.
*/
protected void sendBuffer() {
try {
MimeBodyPart part = new MimeBodyPart();
StringBuffer sbuf = new StringBuffer();
String t = layout.getHeader();
if (t != null)
sbuf.append(t);
int len = cb.length();
for (int i = 0; i < len; i++) {
LoggingEvent event = cb.get();
sbuf.append(layout.format(event));
if (layout.ignoresThrowable()) {
String[] s = event.getThrowableStrRep();
if (s != null) {
for (int j = 0; j < s.length; j++) {
sbuf.append(s[j]);
sbuf.append(Layout.LINE_SEP);
}
}
}
}
t = layout.getFooter();
if (t != null)
sbuf.append(t);
part.setContent(sbuf.toString(), layout.getContentType());
Multipart mp = new MimeMultipart();
mp.addBodyPart(part);
msg.setContent(mp);
msg.setSentDate(new Date());
send(msg);
} catch (Exception e) {
LogLog.error("Error occured while sending e-mail notification.", e);
}
}
/**
* Pulled email send stuff i.e. Transport.send()/Transport.sendMessage(). So
* that on required this logic can be enhanced.
*
* #param msg
* Email Message
* #throws MessagingException
*/
protected void send(Message msg) throws MessagingException {
SMTPTransport t = (SMTPTransport) session.getTransport("smtps");
try {
t.connect(getSMTPHost(), getSMTPUsername(), getSMTPPassword());
t.sendMessage(msg, msg.getAllRecipients());
} finally {
System.out.println("Response: " + t.getLastServerResponse());
t.close();
}
}
}
How I can instantiate of this appender on my log4j.properties configuration ??
Do you need to programatically add the Appender?
Check the following post
I want to modify or remove the "Message-ID" header when replying to an email with Javamail. After some research I found out I need to create a custom class that extends MimeMessage. Here is the class that I have created.
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
class MyMessage extends MimeMessage
{
public MyMessage(Session session)
{
super(session);
}
#Override
protected void updateMessageID() throws MessagingException {
removeHeader("Message-Id");
}
}
The code below is related to fetching the messages
public List<EmailSenderInfo> checkEmail() throws Exception
{
String host = "HOST";
String username = "MYUSERNAME";
String password = "MYPASS";
List<EmailSenderInfo> emailSenderList = new ArrayList<EmailSenderInfo>();
Properties properties = System.getProperties();
properties.setProperty("mail.store.protocol", "imaps");
Session session = Session.getDefaultInstance(properties);
Store store = session.getStore("imaps");
store.connect(host, username, password);
/*
* Folder[] f = store.getDefaultFolder().list(); for (Folder fd : f)
* System.out.println(">> " + fd.getName());
*/
Folder folder = store.getFolder("INBOX");
if (!folder.exists())
{
System.out.println("No INBOX...");
System.exit(0);
}
folder.open(Folder.READ_WRITE);
Message[] msg = folder.getMessages();
if (msg.length < 1)
{
System.out.println("No new messages!");
throw new Exception("No new messages!");
}
for (int i = 0; i < msg.length; i++)
{
if (!msg[i].isSet(Flag.SEEN))
{
EmailSenderInfo emailSenderInfo = new EmailSenderInfo();
emailSenderInfo.message = msg[i];
System.out.println("------------ Message " + (i + 1) + " ------------");
// String from = InternetAddress.toString(msg[i].getFrom());
Address[] fromArray = msg[i].getFrom();
InternetAddress fromInternetAddress = (InternetAddress) fromArray[0];
String from = fromInternetAddress.getAddress();
String fromName = fromInternetAddress.getPersonal();
if (fromName != null)
{
emailSenderInfo.fromName = fromName;
}
if (from != null)
{
// System.out.println("From: " + from);
emailSenderInfo.from = from;
}
// String replyTo = InternetAddress.toString(msg[i].getReplyTo());
Address[] replyToArray = msg[i].getFrom();
InternetAddress ReplyToInternetAddress = (InternetAddress) replyToArray[0];
String replyTo = ReplyToInternetAddress.getAddress();
String replyToName = ReplyToInternetAddress.getPersonal();
if (replyTo != null)
{
// System.out.println("Reply-to: " + replyTo);
emailSenderInfo.replyTo = replyTo;
}
if (replyToName != null)
{
// System.out.println("Reply-to: " + replyTo);
emailSenderInfo.replyToName = replyToName;
}
String to = InternetAddress.toString(msg[i].getRecipients(Message.RecipientType.TO));
if (to != null)
{
// System.out.println("To: " + to);
emailSenderInfo.to = to;
}
String subject = msg[i].getSubject();
if (subject != null)
{
// System.out.println("Subject: " + subject);
emailSenderInfo.subject = subject;
}
Date sentDate = msg[i].getSentDate();
if (sentDate != null)
{
System.out.println("Sent: " + sentDate);
emailSenderInfo.sentDate = sentDate;
}
String bodyHtml = "";
// get content
Multipart multipart = (Multipart) msg[i].getContent();
for (int x = 0; x < multipart.getCount(); x++)
{
BodyPart bodyPart = multipart.getBodyPart(x);
String disposition = bodyPart.getDisposition();
if (Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()))
{
// dealing with attachments only
System.out.println("Mail has some attachment : ");
DataHandler handler = bodyPart.getDataHandler();
System.out.println("file name : " + handler.getName());
System.out.println("ddddd: " + bodyPart.getContent().toString());
}
else
{
String classType = bodyPart.getContent().getClass().toString();
if (classType.contains("java.lang.String"))
{
bodyHtml = bodyPart.getContent().toString();
}
else if (classType.contains("javax.mail.internet.MimeMultipart"))
{
MimeMultipart bodyContent = (MimeMultipart) bodyPart.getContent();
for (int b = 0; b < bodyContent.getCount(); b++)
{
IMAPBodyPart imapBody = (IMAPBodyPart) bodyContent.getBodyPart(b);
System.out.println("1: " + imapBody.getContent());
bodyHtml = imapBody.getContent().toString();
// System.out.println("2: " + bodyContent.getBodyPart(b));
// System.out.println("3: " + bodyPart.getContent().toString());
}
}
}
emailSenderInfo.bodyHtml = bodyHtml;
}
MyMessage reply = (MyMessage) msg[i].reply(false);
emailSenderInfo.reply = reply;
// reply.setFrom(msg[i].getFrom()[0]);
MimeMessage orig = (MimeMessage) msg[i];
StringBuffer buffer = new StringBuffer("Thanks\n\n");
if (orig.isMimeType("text/plain"))
{
String content = (String) orig.getContent();
StringReader contentReader = new StringReader(content);
BufferedReader br = new BufferedReader(contentReader);
String contentLine;
while ((contentLine = br.readLine()) != null)
{
buffer.append("> ");
buffer.append(contentLine);
buffer.append("\r\n");
}
}
// Set the reply content
// reply.setText(buffer.toString());
// emailSenderInfo.reply = reply;
emailSenderList.add(emailSenderInfo);
// System.out.println();
}// end if unread
}
folder.close(true);
store.close();
return emailSenderList;
}
I have two methods in my program. One of them checks mail and another one which replies to emails.
Message reply = msg[i].reply(false);
"reply" gets passed to this method along with other parameters.
public void sendReply(String from, String replyTo, Message reply, String messageReply, Boolean attachment) throws Exception
{
String host = "MYHOST";
String username = "MYUSERNAME";
String pass = "MYPASSWORD";
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", "true"); // added this line
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", username);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage mimeReply = (MimeMessage) reply;
mimeReply.setFrom((Address) InternetAddress.parse(from)[0]);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(messageReply, "text/html");
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
if (attachment)
{
messageBodyPart = new MimeBodyPart();
String filename = "test.jpg";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
}
mimeReply.setContent(multipart);
Transport transport = session.getTransport("smtp");
transport.connect(host, username, pass);
transport.sendMessage(mimeReply, InternetAddress.parse(replyTo));
transport.close();
System.out.println("Message Sent!");
}
I have to use the MyMessage class in order to remove the "Message-ID" header. I have tried the following
MyMessage mimeReply = (MyMessage) reply;
But I get the following error in runtime
java.lang.ClassCastException: javax.mail.internet.MimeMessage cannot be cast to javamailer.MyMessage
How can use "MyMessage" class so I can remove the "Message-ID" header with the reply message?
You can try the following:
When replying to an email:
When you create a message create, right now it should be like:
MimeMessage msg = new MimeMessage(session);
change it to,
MyMessage msg = new MyMessage(session);
When checking email you don't need to remove the header as that message is already in the mailbox, what I think you need to do is when replying to a mail at that instance for the name mail instantiate like :
MyMessage msg = new MyMessage(session);
msg.updateMessageID();
Since you are using reference to existing message:
You can do something like:
Create a new constructor:
public MyMessage (MimeMessage message) {
super(message);
}
When replying:
MyMessage mimeReply = new MyMessage(reply);
mimeReply.updateMessageID();
Then send the mimeReply NOT reply.