Skip to content

Instantly share code, notes, and snippets.

@northcoder-repo
Created September 7, 2020 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save northcoder-repo/79d3ef34f23819bcb9eef58c24e6f00b to your computer and use it in GitHub Desktop.
Save northcoder-repo/79d3ef34f23819bcb9eef58c24e6f00b to your computer and use it in GitHub Desktop.
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