use of javax.mail.Multipart in project SpringStepByStep by JavaProgrammerLB.
the class SendHTMLEmailWithTemplate method main.
public static void main(String[] args) throws Exception {
Properties props = new Properties();
try {
props.load(new FileInputStream(new File("settings.properties")));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
Session session = Session.getDefaultInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "******");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from@gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@gmail.com"));
message.setSubject("Testing Subject");
BodyPart body = new MimeBodyPart();
// freemarker stuff.
Configuration cfg = new Configuration();
Template template = cfg.getTemplate("html-mail-template.ftl");
Map<String, String> rootMap = new HashMap<String, String>();
rootMap.put("to", "liubei");
rootMap.put("body", "Sample html email using freemarker");
rootMap.put("from", "liubei");
Writer out = new StringWriter();
template.process(rootMap, out);
// freemarker stuff ends.
/* you can add html tags in your text to decorate it. */
body.setContent(out.toString(), "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(body);
body = new MimeBodyPart();
String filename = "hello.txt";
DataSource source = new FileDataSource(filename);
body.setDataHandler(new DataHandler(source));
body.setFileName(filename);
multipart.addBodyPart(body);
message.setContent(multipart, "text/html;charset=utf-8");
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
System.out.println("Done....");
}
use of javax.mail.Multipart in project google-app-engine-jappstart by taylorleese.
the class MailService method sendActivationEmail.
/**
* Sends the activation e-mail to the given user.
*
* @param user the user
* @param locale the locale
* @throws MessagingException messaging exception
*/
public final void sendActivationEmail(final UserAccount user, final String locale) throws MessagingException {
final Properties props = new Properties();
final Session session = Session.getDefaultInstance(props, null);
final Message message = new MimeMessage(session);
final Multipart multipart = new MimeMultipart();
final MimeBodyPart htmlPart = new MimeBodyPart();
final MimeBodyPart textPart = new MimeBodyPart();
message.setFrom(new InternetAddress(getFromAddress()));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
message.setSubject(messageSource.getMessage("mail.subject", null, new Locale(locale)));
textPart.setContent(messageSource.getMessage("mail.body.txt", new Object[] { getHostname(), user.getActivationKey() }, new Locale(locale)), "text/plain");
htmlPart.setContent(messageSource.getMessage("mail.body.html", new Object[] { getHostname(), user.getActivationKey() }, new Locale(locale)), "text/html");
multipart.addBodyPart(textPart);
multipart.addBodyPart(htmlPart);
message.setContent(multipart);
Transport.send(message);
}
use of javax.mail.Multipart in project openolat by klemens.
the class MailManagerImpl method createForwardMimeMessage.
private MimeMessage createForwardMimeMessage(Address from, Address to, String subject, String body, List<DBMailAttachment> attachments, MailerResult result) {
try {
MimeMessage msg = createMessage(subject, from);
if (to != null) {
msg.addRecipient(RecipientType.TO, to);
}
if (attachments != null && !attachments.isEmpty()) {
// with attachment use multipart message
Multipart multipart = new MimeMultipart("mixed");
// 1) add body part
if (StringHelper.isHtml(body)) {
Multipart alternativePart = createMultipartAlternative(body);
MimeBodyPart wrap = new MimeBodyPart();
wrap.setContent(alternativePart);
multipart.addBodyPart(wrap);
} else {
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(body);
multipart.addBodyPart(messageBodyPart);
}
// 2) add attachments
for (DBMailAttachment attachment : attachments) {
// abort if attachment does not exist
if (attachment == null || attachment.getSize() <= 0) {
result.setReturnCode(MailerResult.ATTACHMENT_INVALID);
log.error("Tried to send mail wit attachment that does not exist::" + (attachment == null ? null : attachment.getName()), null);
return msg;
}
BodyPart messageBodyPart = new MimeBodyPart();
VFSLeaf data = getAttachmentDatas(attachment);
DataSource source = new VFSDataSource(attachment.getName(), attachment.getMimetype(), data);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(attachment.getName());
multipart.addBodyPart(messageBodyPart);
}
// Put parts in message
msg.setContent(multipart);
} else {
// without attachment everything is easy, just set as text
if (StringHelper.isHtml(body)) {
msg.setContent(createMultipartAlternative(body));
} else {
msg.setText(body, "utf-8");
}
}
msg.setSentDate(new Date());
msg.saveChanges();
return msg;
} catch (MessagingException | UnsupportedEncodingException e) {
log.error("", e);
return null;
}
}
use of javax.mail.Multipart in project openolat by klemens.
the class MailManagerImpl method createMimeMessage.
@Override
public MimeMessage createMimeMessage(Address from, Address[] tos, Address[] ccs, Address[] bccs, String subject, String body, List<File> attachments, MailerResult result) {
if (from == null || ((tos == null || tos.length == 0) && ((ccs == null || ccs.length == 0)) && (bccs == null || bccs.length == 0)))
return null;
try {
MimeMessage msg = createMessage(subject, from);
if (tos != null && tos.length > 0) {
msg.addRecipients(RecipientType.TO, tos);
}
if (ccs != null && ccs.length > 0) {
msg.addRecipients(RecipientType.CC, ccs);
}
if (bccs != null && bccs.length > 0) {
msg.addRecipients(RecipientType.BCC, bccs);
}
if (attachments != null && !attachments.isEmpty()) {
// with attachment use multipart message
Multipart multipart = new MimeMultipart("mixed");
// 1) add body part
if (StringHelper.isHtml(body)) {
Multipart alternativePart = createMultipartAlternative(body);
MimeBodyPart wrap = new MimeBodyPart();
wrap.setContent(alternativePart);
multipart.addBodyPart(wrap);
} else {
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(body);
multipart.addBodyPart(messageBodyPart);
}
// 2) add attachments
for (File attachmentFile : attachments) {
// abort if attachment does not exist
if (attachmentFile == null || !attachmentFile.exists()) {
result.setReturnCode(MailerResult.ATTACHMENT_INVALID);
log.error("Tried to send mail wit attachment that does not exist::" + (attachmentFile == null ? null : attachmentFile.getAbsolutePath()), null);
return msg;
}
BodyPart filePart = new MimeBodyPart();
DataSource source = new FileDataSource(attachmentFile);
filePart.setDataHandler(new DataHandler(source));
filePart.setFileName(attachmentFile.getName());
multipart.addBodyPart(filePart);
}
// Put parts in message
msg.setContent(multipart);
} else {
// without attachment everything is easy, just set as text
if (StringHelper.isHtml(body)) {
msg.setContent(createMultipartAlternative(body));
} else {
msg.setText(body, "utf-8");
}
}
msg.setSentDate(new Date());
msg.saveChanges();
return msg;
} catch (AddressException e) {
result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR);
log.error("", e);
return null;
} catch (MessagingException e) {
result.setReturnCode(MailerResult.SEND_GENERAL_ERROR);
log.error("", e);
return null;
} catch (UnsupportedEncodingException e) {
result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR);
log.error("", e);
return null;
}
}
use of javax.mail.Multipart in project ddf by codice.
the class SmtpClientImplITCaseTest method testSendWithAttachments.
@Test
public void testSendWithAttachments() throws IOException, MessagingException, ExecutionException, InterruptedException {
int port = findAvailablePort();
SimpleSmtpServer server = SimpleSmtpServer.start(port);
SmtpClientImpl emailService = new SmtpClientImpl(null);
emailService.setSecurityLogger(mock(SecurityLogger.class));
emailService.setHostName(HOSTNAME);
emailService.setPortNumber(port);
File tmpFile = folder.newFile("email.txt");
try (OutputStream os = new FileOutputStream(tmpFile)) {
os.write(ATTACHMENT_TEXT.getBytes());
}
Session session = emailService.createSession();
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setFrom(new InternetAddress(FROM_ADDR));
mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(TO_ADDR));
mimeMessage.setSubject(SUBJECT);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(BODY);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(tmpFile)));
messageBodyPart.setFileName(ATTACHMENT_FILENAME);
multipart.addBodyPart(messageBodyPart);
mimeMessage.setContent(multipart);
emailService.send(mimeMessage).get();
server.stop();
List<SmtpMessage> emails = server.getReceivedEmails();
assertThat(emails, hasSize(1));
SmtpMessage email = emails.get(0);
assertNotNull("The email was null.", email);
assertThat(email.getHeaderValue(SUBJECT_HEADER), is(SUBJECT));
assertThat(email.getHeaderValue(FROM_HEADER), containsString(FROM_ADDR));
assertThat(email.getHeaderValue(TO_HEADER), containsString(TO_ADDR));
assertThat(email.getBody(), containsString(BODY));
assertThat(email.getBody(), containsString(ATTACHMENT_TEXT));
assertThat(email.getBody(), containsString(ATTACHMENT_FILENAME));
}
Aggregations