Это неотъемлемо невозможно в текущей реализации: имена локальных переменных недоступны во время выполнения - могут храниться как символы отладки, но также могут быть удалены. (Имена переменных-членов, но это не то, что вы здесь описываете).
Пожалуйста, измените код на это:
String to = "mail@example.com";
// Sender's email ID needs to be mentioned
String from = "sender@example.com";
final String username = "user";//change accordingly
final String password = "pwd";//change accordingly
// Assuming you are sending email through outlook mail
String host = "outlook.office365.com";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// Create a default MimeMessage object.
Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(msgSubject);
message.setSentDate(new java.util.Date());
MimeBodyPart messageBodyPart = new MimeBodyPart();
String htmlText = "<p>Hi Team,</p> <p>Please find the Report for the day </p> <p> </p> <img src=\"cid:image\"> <p> Regards, </p> <p> Team</p>";
messageBodyPart.setContent(htmlText, "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
MimeBodyPart imagePart = new MimeBodyPart();
imagePart.setHeader("Content-ID", "<image>");
//add this to avoid unwanted attachment.
imagePart.setDisposition(MimeBodyPart.INLINE);
imagePart.attachFile(new File("C:\\abc.png"));
multipart.addBodyPart(imagePart);
message.setContent(multipart);
Transport.send(message);
} catch (MessagingException | IOException ex) {
throw new RuntimeException(e);
}