use of javax.mail.Multipart in project MyBaseApplication by BanShouWeng.
the class SimpleMailSender method sendHtmlMail.
public static boolean sendHtmlMail(MailSenderInfo mailInfo) {
MyAuthenticator authenticator = null;
Properties pro = mailInfo.getProperties();
if (mailInfo.isValidate()) {
authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
}
Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
try {
Message mailMessage = new MimeMessage(sendMailSession);
Address from = new InternetAddress(mailInfo.getFromAddress());
mailMessage.setFrom(from);
Address to = new InternetAddress(mailInfo.getToAddress());
mailMessage.setRecipient(Message.RecipientType.TO, to);
mailMessage.setSubject(mailInfo.getSubject());
mailMessage.setSentDate(new Date());
Multipart mainPart = new MimeMultipart();
BodyPart html = new MimeBodyPart();
Log.d("==error==", mailInfo.getContent());
html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
mainPart.addBodyPart(html);
mailMessage.setContent(mainPart);
Transport.send(mailMessage);
return true;
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
use of javax.mail.Multipart in project contribution by checkstyle.
the class MailingListPublisher method publish.
/**
* Publish post.
* @throws MessagingException if an error occurs while publishing.
* @throws IOException if there are problems with reading file with the post text.
*/
public void publish() throws MessagingException, IOException {
final Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.host", SMTP_HOST);
props.put("mail.smtp.user", username);
props.put("mail.smtp.password", password);
props.put("mail.smtp.port", SMTP_PORT);
props.put("mail.smtp.auth", true);
final Session session = Session.getInstance(props, null);
final MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setSubject(String.format(SUBJECT_TEMPLATE, releaseNumber));
mimeMessage.setFrom(new InternetAddress(username));
mimeMessage.addRecipients(Message.RecipientType.TO, InternetAddress.parse(RECIPIENT_ADDRESS));
final String post = new String(Files.readAllBytes(Paths.get(postFilename)), StandardCharsets.UTF_8);
final BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(post, "text/plain");
final Multipart multipart = new MimeMultipart("alternative");
multipart.addBodyPart(messageBodyPart);
mimeMessage.setContent(multipart);
final Transport transport = session.getTransport("smtp");
transport.connect(SMTP_HOST, username, password);
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
}
use of javax.mail.Multipart in project jbpm-work-items by kiegroup.
the class SendMailWorkitemHandler method createEmailWithAttachment.
public MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText, Document attachment) throws MessagingException, IOException {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
MimeMessage email = new MimeMessage(session);
email.setFrom(new InternetAddress(from));
email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
email.setSubject(subject);
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(bodyText, "text/plain");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);
if (attachment != null) {
mimeBodyPart = new MimeBodyPart();
DataSource source = new InputStreamDataSource(new ByteArrayInputStream(attachment.getContent()));
mimeBodyPart.setDataHandler(new DataHandler(source));
mimeBodyPart.setFileName(attachment.getName());
multipart.addBodyPart(mimeBodyPart);
}
email.setContent(multipart);
return email;
}
use of javax.mail.Multipart in project jbpm by kiegroup.
the class EmailNotificationListener method onNotification.
@Override
public void onNotification(NotificationEvent event, UserInfo userInfo) {
if (userInfo == null || mailSession == null) {
logger.info("Missing mail session or userinfo - skipping email notification listener processing");
return;
}
if (event.getNotification() instanceof EmailNotification) {
EmailNotification notification = (EmailNotification) event.getNotification();
Task task = event.getTask();
// group users into languages
Map<String, List<User>> users = new HashMap<String, List<User>>();
for (OrganizationalEntity entity : notification.getBusinessAdministrators()) {
if (entity instanceof Group) {
buildMapByLanguage(users, (Group) entity, userInfo);
} else {
buildMapByLanguage(users, (User) entity, userInfo);
}
}
for (OrganizationalEntity entity : notification.getRecipients()) {
if (entity instanceof Group) {
buildMapByLanguage(users, (Group) entity, userInfo);
} else {
buildMapByLanguage(users, (User) entity, userInfo);
}
}
Map<String, Object> variables = event.getContent();
Map<? extends Language, ? extends EmailNotificationHeader> headers = notification.getEmailHeaders();
for (Iterator<Map.Entry<String, List<User>>> it = users.entrySet().iterator(); it.hasNext(); ) {
try {
Map.Entry<String, List<User>> entry = it.next();
Language lang = TaskModelProvider.getFactory().newLanguage();
lang.setMapkey(entry.getKey());
EmailNotificationHeader header = headers.get(lang);
Message msg = new MimeMessage(mailSession);
Set<String> toAddresses = new HashSet<String>();
for (User user : entry.getValue()) {
String emailAddress = userInfo.getEmailForEntity(user);
if (emailAddress != null && !toAddresses.contains(emailAddress)) {
msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse(emailAddress, false));
toAddresses.add(emailAddress);
} else {
logger.warn("Email address not found for user {}", user.getId());
}
}
if (header.getFrom() != null && header.getFrom().trim().length() > 0) {
User user = TaskModelProvider.getFactory().newUser();
((InternalOrganizationalEntity) user).setId(header.getFrom());
msg.setFrom(new InternetAddress(userInfo.getEmailForEntity(user)));
} else {
msg.setFrom(new InternetAddress(mailSession.getProperty("mail.from")));
}
if (header.getReplyTo() != null && header.getReplyTo().trim().length() > 0) {
User user = TaskModelProvider.getFactory().newUser();
((InternalOrganizationalEntity) user).setId(header.getReplyTo());
msg.setReplyTo(new InternetAddress[] { new InternetAddress(userInfo.getEmailForEntity(user)) });
} else if (mailSession.getProperty("mail.replyto") != null) {
msg.setReplyTo(new InternetAddress[] { new InternetAddress(mailSession.getProperty("mail.replyto")) });
}
Map<String, Object> vars = new HashMap<String, Object>();
vars.put("doc", variables);
// add internal items to be able to reference them in templates
vars.put("processInstanceId", task.getTaskData().getProcessInstanceId());
vars.put("processSessionId", task.getTaskData().getProcessSessionId());
vars.put("workItemId", task.getTaskData().getWorkItemId());
vars.put("expirationTime", task.getTaskData().getExpirationTime());
vars.put("taskId", task.getId());
if (task.getPeopleAssignments() != null) {
vars.put("owners", task.getPeopleAssignments().getPotentialOwners());
}
String subject = (String) TemplateRuntime.eval(header.getSubject(), vars);
String body = (String) TemplateRuntime.eval(header.getBody(), vars);
if (variables.containsKey("attachments")) {
Multipart multipart = new MimeMultipart();
// prepare body as first mime body part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(body, "text/html")));
multipart.addBodyPart(messageBodyPart);
List<String> attachments = getAttachements(variables.get("attachments"));
for (String attachment : attachments) {
MimeBodyPart attachementBodyPart = new MimeBodyPart();
URL attachmentUrl = getAttachemntURL(attachment);
String contentType = MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(attachmentUrl.getFile());
attachementBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(attachmentUrl.openStream(), contentType)));
String fileName = new File(attachmentUrl.getFile()).getName();
attachementBodyPart.setFileName(fileName);
attachementBodyPart.setContentID("<" + fileName + ">");
multipart.addBodyPart(attachementBodyPart);
}
// Put parts in message
msg.setContent(multipart);
} else {
msg.setDataHandler(new DataHandler(new ByteArrayDataSource(body, "text/html")));
}
msg.setSubject(subject);
msg.setHeader("X-Mailer", "jbpm human task service");
msg.setSentDate(new Date());
Transport.send(msg);
} catch (Exception e) {
logger.error("Unable to send email notification due to {}", e.getMessage());
logger.debug("Stacktrace:", e);
}
}
}
}
use of javax.mail.Multipart in project scout.rt by eclipse.
the class MailHelperTest method createMimeMessageUsingUnknownEncoding.
protected MimeMessage createMimeMessageUsingUnknownEncoding() throws IOException, MessagingException {
MailMessage definition = new MailMessage().withBodyPlainText("a");
MimeMessage mimeMessage = BEANS.get(MailHelper.class).createMimeMessage(definition);
Object multipart0 = mimeMessage.getContent();
Assert.assertTrue(multipart0 instanceof Multipart);
Multipart multipart = (Multipart) multipart0;
BodyPart plaintextPart = multipart.getBodyPart(0);
plaintextPart.setHeader(MailHelper.CONTENT_TYPE_ID, "text/plain; charset=\"" + RARE_UNKNOWN_CHARSET + "\"");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
mimeMessage.writeTo(bos);
mimeMessage = new MimeMessage(null, new ByteArrayInputStream(bos.toByteArray()));
return mimeMessage;
}
Aggregations