Created
September 7, 2020 14:14
-
-
Save northcoder-repo/79d3ef34f23819bcb9eef58c24e6f00b to your computer and use it in GitHub Desktop.
Spring Mailer Example for SO question https://stackoverflow.com/questions/63778475/java-mail-inline-image-is-not-shown-in-email
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.UnsupportedEncodingException; | |
import java.util.logging.Level; | |
import java.util.logging.Logger; | |
import javax.activation.DataSource; | |
import javax.activation.FileDataSource; | |
import javax.mail.MessagingException; | |
import javax.mail.internet.MimeMessage; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.mail.javamail.JavaMailSender; | |
import org.springframework.mail.javamail.MimeMessageHelper; | |
import org.springframework.stereotype.Component; | |
@Component | |
public class MySpringMailer { | |
static final String FROM = "donotreply@me.org"; | |
static final String FROMNAME = "Test Person"; | |
static final String TO = "me@here.com"; | |
static final String SUBJECT = "Welcome to ABC"; | |
static final String BODY = String.join(System.getProperty("line.separator"), | |
"<html><head></head><body><img src=\"cid:image_01\"></html> <br>" | |
+ "Welcome to ABC and have a really great experience."); | |
@Autowired | |
private JavaMailSender javaMailSender; | |
public void sendSpringEmailWithInlineImage() { | |
MimeMessage msg = javaMailSender.createMimeMessage(); | |
try { | |
MimeMessageHelper helper = new MimeMessageHelper(msg, true); // true = multipart | |
helper.setFrom(FROM, FROMNAME); | |
helper.setTo(TO); | |
helper.setSubject(SUBJECT); | |
helper.setText(BODY, true); // true = HTML | |
DataSource res = new FileDataSource("/path/to/logo.png"); | |
helper.addInline("image_01", res); | |
} catch (UnsupportedEncodingException | MessagingException ex) { | |
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); | |
} | |
javaMailSender.send(msg); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment