use of javax.mail.internet.MimeMessage in project webofneeds by researchstudio-sat.
the class Message2MailAction method doRun.
@Override
protected void doRun(Event event, EventListener executingListener) throws Exception {
EventListenerContext ctx = getEventListenerContext();
if (event instanceof MessageFromOtherNeedEvent && ctx.getBotContextWrapper() instanceof MailBotContextWrapper) {
MailBotContextWrapper botContextWrapper = (MailBotContextWrapper) ctx.getBotContextWrapper();
Connection con = ((MessageFromOtherNeedEvent) event).getCon();
URI responseTo = con.getNeedURI();
URI remoteNeedUri = con.getRemoteNeedURI();
MimeMessage originalMail = botContextWrapper.getMimeMessageForURI(responseTo);
logger.debug("Someone sent a message for URI: " + responseTo + " sending a mail to the creator: " + MailContentExtractor.getFromAddressString(originalMail));
WonMimeMessage answerMessage = mailGenerator.createMessageMail(originalMail, responseTo, remoteNeedUri, con.getConnectionURI());
botContextWrapper.addMailIdWonURIRelation(answerMessage.getMessageID(), new WonURI(con.getConnectionURI(), UriType.CONNECTION));
sendChannel.send(new GenericMessage<>(answerMessage));
} else {
logger.debug("event was not of type MessageFromOtherNeedEvent");
}
}
use of javax.mail.internet.MimeMessage in project webofneeds by researchstudio-sat.
the class BotContextTests method testPutAndRetrieveGenericObjects.
@Test
public void testPutAndRetrieveGenericObjects() throws MessagingException, IOException, ClassNotFoundException {
// List
botContext.dropCollection("uriList");
LinkedList<URI> uriList = new LinkedList<>();
uriList.add(URI1);
uriList.add(URI1);
uriList.add(URI2);
uriList.add(URI3);
botContext.saveToObjectMap("uriList", "list1", uriList);
List<URI> uriListCopy = (List<URI>) botContext.loadFromObjectMap("uriList", "list1");
Assert.assertEquals(uriList, uriListCopy);
// HashMap needs to be serialized (here only non-complex keys are allowed in maps)
botContext.dropCollection("uriMap");
HashMap<String, URI> uriHashMap = new HashMap<>();
uriHashMap.put(URI1.toString(), URI1);
uriHashMap.put(URI2.toString(), URI1);
uriHashMap.put(URI3.toString(), URI3);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(uriHashMap);
botContext.saveToObjectMap("uriMap", "map1", os.toByteArray());
byte[] byteMsg = (byte[]) botContext.loadFromObjectMap("uriMap", "map1");
ByteArrayInputStream is = new ByteArrayInputStream(byteMsg);
ObjectInputStream ois = new ObjectInputStream(is);
HashMap<String, URI> uriHashMapCopy = (HashMap<String, URI>) ois.readObject();
Assert.assertEquals(uriHashMap, uriHashMapCopy);
oos.close();
os.close();
ois.close();
is.close();
// TreeMap is serializable
TreeMap<String, URI> uriTreeMap = new TreeMap<>();
uriTreeMap.put(URI1.toString(), URI2);
uriTreeMap.put(URI2.toString(), URI3);
uriTreeMap.put(URI3.toString(), URI1);
// overwrite the HashMap entry from the previous step
botContext.saveToObjectMap("uriMap", "map1", uriTreeMap);
Map<String, URI> uriTreeMapCopy = (Map<String, URI>) botContext.loadFromObjectMap("uriMap", "map1");
Assert.assertEquals(uriTreeMap, uriTreeMapCopy);
// MimeMessage cannot be serialized directly => has to be serialized manually first
botContext.dropCollection("mime");
Properties props = new Properties();
MimeMessage message = new MimeMessage(Session.getDefaultInstance(props, null));
message.addHeader("test1", "test2");
message.addHeaderLine("test3");
message.addRecipients(Message.RecipientType.TO, "mail@test.test");
message.setText("text");
message.setSubject("text1");
message.setDescription("text2");
message.setSentDate(new Date());
os = new ByteArrayOutputStream();
message.writeTo(os);
botContext.saveToObjectMap("mime", "mime1", os.toByteArray());
byteMsg = (byte[]) botContext.loadFromObjectMap("mime", "mime1");
is = new ByteArrayInputStream(byteMsg);
MimeMessage messageCopy = new MimeMessage(Session.getDefaultInstance(props, null), is);
Assert.assertEquals(message.getHeader("test1")[0], messageCopy.getHeader("test1")[0]);
Assert.assertEquals(message.getAllHeaderLines().nextElement(), messageCopy.getAllHeaderLines().nextElement());
Assert.assertEquals(message.getRecipients(Message.RecipientType.TO)[0], messageCopy.getRecipients(Message.RecipientType.TO)[0]);
Assert.assertEquals(message.getSubject(), messageCopy.getSubject());
Assert.assertEquals(message.getDescription(), messageCopy.getDescription());
Assert.assertEquals(message.getSentDate(), messageCopy.getSentDate());
oos.close();
os.close();
ois.close();
is.close();
}
use of javax.mail.internet.MimeMessage in project quickutil by quickutil.
the class MailUtil method send.
public static boolean send(String[] toMails, String[] ccMails, String[] bccMails, String title, String text, String[] attachments) {
try {
InternetAddress[] toAddresses = new InternetAddress[toMails.length];
for (int i = 0; i < toMails.length; i++) {
toAddresses[i] = new InternetAddress(toMails[i]);
}
if (ccMails == null)
ccMails = new String[0];
InternetAddress[] ccAddresses = new InternetAddress[ccMails.length];
for (int i = 0; i < ccMails.length; i++) {
ccAddresses[i] = new InternetAddress(ccMails[i]);
}
if (bccMails == null)
bccMails = new String[0];
InternetAddress[] bccAddresses = new InternetAddress[bccMails.length];
for (int i = 0; i < bccMails.length; i++) {
bccAddresses[i] = new InternetAddress(bccMails[i]);
}
Session mailSession = Session.getInstance(mailProperties, authenticator);
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(mailProperties.getProperty("mail.user")));
message.setSubject(title);
message.setRecipients(RecipientType.TO, toAddresses);
message.setRecipients(RecipientType.CC, ccAddresses);
message.setRecipients(RecipientType.BCC, bccAddresses);
Multipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(text, "text/html;charset=UTF-8");
multipart.addBodyPart(messageBodyPart);
for (String filePath : attachments) {
MimeBodyPart attachPart = new MimeBodyPart();
File file = new File(filePath);
if (!file.exists()) {
throw new RuntimeException("not exist file: " + filePath);
}
attachPart.attachFile(filePath);
multipart.addBodyPart(attachPart);
}
message.setContent(multipart);
message.saveChanges();
Transport.send(message);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
use of javax.mail.internet.MimeMessage in project cas by apereo.
the class CommunicationsManager method email.
/**
* Email.
*
* @param text the text
* @param from the from
* @param subject the subject
* @param to the to
* @param cc the cc
* @param bcc the bcc
* @return the boolean
*/
public boolean email(final String text, final String from, final String subject, final String to, final String cc, final String bcc) {
try {
if (!isMailSenderDefined() || StringUtils.isBlank(text) || StringUtils.isBlank(from) || StringUtils.isBlank(subject) || StringUtils.isBlank(to)) {
LOGGER.warn("Could not send email to [{}] because either no address/subject/text is found or email settings are not configured.", to);
return false;
}
final MimeMessage message = this.mailSender.createMimeMessage();
final MimeMessageHelper helper = new MimeMessageHelper(message);
helper.setTo(to);
helper.setText(text);
helper.setSubject(subject);
helper.setFrom(from);
helper.setPriority(1);
if (StringUtils.isNotBlank(cc)) {
helper.setCc(cc);
}
if (StringUtils.isNotBlank(bcc)) {
helper.setBcc(bcc);
}
this.mailSender.send(message);
return true;
} catch (final Exception ex) {
LOGGER.error(ex.getMessage(), ex);
}
return false;
}
use of javax.mail.internet.MimeMessage in project nifi by apache.
the class ExtractEmailAttachments method onTrigger.
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
final ComponentLog logger = getLogger();
final FlowFile originalFlowFile = session.get();
if (originalFlowFile == null) {
return;
}
final List<FlowFile> attachmentsList = new ArrayList<>();
final List<FlowFile> invalidFlowFilesList = new ArrayList<>();
final List<FlowFile> originalFlowFilesList = new ArrayList<>();
final String requireStrictAddresses = "false";
session.read(originalFlowFile, new InputStreamCallback() {
@Override
public void process(final InputStream rawIn) throws IOException {
try (final InputStream in = new BufferedInputStream(rawIn)) {
Properties props = new Properties();
props.put("mail.mime.address.strict", requireStrictAddresses);
Session mailSession = Session.getInstance(props);
MimeMessage originalMessage = new MimeMessage(mailSession, in);
MimeMessageParser parser = new MimeMessageParser(originalMessage).parse();
// RFC-2822 determines that a message must have a "From:" header
// if a message lacks the field, it is flagged as invalid
Address[] from = originalMessage.getFrom();
if (from == null) {
throw new MessagingException("Message failed RFC-2822 validation: No Sender");
}
Date sentDate = originalMessage.getSentDate();
if (sentDate == null) {
// Throws MessageException due to lack of minimum required headers
throw new MessagingException("Message failed RFC2822 validation: No Sent Date");
}
originalFlowFilesList.add(originalFlowFile);
if (parser.hasAttachments()) {
final String originalFlowFileName = originalFlowFile.getAttribute(CoreAttributes.FILENAME.key());
try {
for (final DataSource data : parser.getAttachmentList()) {
FlowFile split = session.create(originalFlowFile);
final Map<String, String> attributes = new HashMap<>();
if (StringUtils.isNotBlank(data.getName())) {
attributes.put(CoreAttributes.FILENAME.key(), data.getName());
}
if (StringUtils.isNotBlank(data.getContentType())) {
attributes.put(CoreAttributes.MIME_TYPE.key(), data.getContentType());
}
String parentUuid = originalFlowFile.getAttribute(CoreAttributes.UUID.key());
attributes.put(ATTACHMENT_ORIGINAL_UUID, parentUuid);
attributes.put(ATTACHMENT_ORIGINAL_FILENAME, originalFlowFileName);
split = session.append(split, new OutputStreamCallback() {
@Override
public void process(OutputStream out) throws IOException {
IOUtils.copy(data.getInputStream(), out);
}
});
split = session.putAllAttributes(split, attributes);
attachmentsList.add(split);
}
} catch (FlowFileHandlingException e) {
// Something went wrong
// Removing splits that may have been created
session.remove(attachmentsList);
// Removing the original flow from its list
originalFlowFilesList.remove(originalFlowFile);
logger.error("Flowfile {} triggered error {} while processing message removing generated FlowFiles from sessions", new Object[] { originalFlowFile, e });
invalidFlowFilesList.add(originalFlowFile);
}
}
} catch (Exception e) {
// Another error hit...
// Removing the original flow from its list
originalFlowFilesList.remove(originalFlowFile);
logger.error("Could not parse the flowfile {} as an email, treating as failure", new Object[] { originalFlowFile, e });
// Message is invalid or triggered an error during parsing
invalidFlowFilesList.add(originalFlowFile);
}
}
});
session.transfer(attachmentsList, REL_ATTACHMENTS);
// As per above code, originalFlowfile may be routed to invalid or
// original depending on RFC2822 compliance.
session.transfer(invalidFlowFilesList, REL_FAILURE);
session.transfer(originalFlowFilesList, REL_ORIGINAL);
if (attachmentsList.size() > 10) {
logger.info("Split {} into {} files", new Object[] { originalFlowFile, attachmentsList.size() });
} else if (attachmentsList.size() > 1) {
logger.info("Split {} into {} files: {}", new Object[] { originalFlowFile, attachmentsList.size(), attachmentsList });
}
}
Aggregations