List of usage examples for javax.mail Session getDefaultInstance
public static synchronized Session getDefaultInstance(Properties props, Authenticator authenticator)
From source file:org.apache.nifi.processors.email.ExtractEmailHeaders.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) { final ComponentLog logger = getLogger(); final List<FlowFile> invalidFlowFilesList = new ArrayList<>(); final List<FlowFile> processedFlowFilesList = new ArrayList<>(); final FlowFile originalFlowFile = session.get(); if (originalFlowFile == null) { return;/* w ww . j a v a2s . c om*/ } final List<String> capturedHeadersList = Arrays .asList(context.getProperty(CAPTURED_HEADERS).getValue().toLowerCase().split(":")); final Map<String, String> attributes = new HashMap<>(); 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(); Session mailSession = Session.getDefaultInstance(props, null); 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(); Date sentDate = originalMessage.getSentDate(); if (from == null || sentDate == null) { // Throws MessageException due to lack of minimum required headers throw new MessagingException("Message failed RFC2822 validation"); } else if (capturedHeadersList.size() > 0) { Enumeration headers = originalMessage.getAllHeaders(); while (headers.hasMoreElements()) { Header header = (Header) headers.nextElement(); if (StringUtils.isNotEmpty(header.getValue()) && capturedHeadersList.contains(header.getName().toLowerCase())) { attributes.put("email.headers." + header.getName().toLowerCase(), header.getValue()); } } } if (Array.getLength(originalMessage.getAllRecipients()) > 0) { for (int toCount = 0; toCount < ArrayUtils .getLength(originalMessage.getRecipients(Message.RecipientType.TO)); toCount++) { attributes.put(EMAIL_HEADER_TO + "." + toCount, originalMessage.getRecipients(Message.RecipientType.TO)[toCount].toString()); } for (int toCount = 0; toCount < ArrayUtils .getLength(originalMessage.getRecipients(Message.RecipientType.BCC)); toCount++) { attributes.put(EMAIL_HEADER_BCC + "." + toCount, originalMessage.getRecipients(Message.RecipientType.BCC)[toCount].toString()); } for (int toCount = 0; toCount < ArrayUtils .getLength(originalMessage.getRecipients(Message.RecipientType.CC)); toCount++) { attributes.put(EMAIL_HEADER_CC + "." + toCount, originalMessage.getRecipients(Message.RecipientType.CC)[toCount].toString()); } } // Incredibly enough RFC-2822 specified From as a "mailbox-list" so an array I returned by getFrom for (int toCount = 0; toCount < ArrayUtils.getLength(originalMessage.getFrom()); toCount++) { attributes.put(EMAIL_HEADER_FROM + "." + toCount, originalMessage.getFrom()[toCount].toString()); } if (StringUtils.isNotEmpty(originalMessage.getMessageID())) { attributes.put(EMAIL_HEADER_MESSAGE_ID, originalMessage.getMessageID()); } if (originalMessage.getReceivedDate() != null) { attributes.put(EMAIL_HEADER_RECV_DATE, originalMessage.getReceivedDate().toString()); } if (originalMessage.getSentDate() != null) { attributes.put(EMAIL_HEADER_SENT_DATE, originalMessage.getSentDate().toString()); } if (StringUtils.isNotEmpty(originalMessage.getSubject())) { attributes.put(EMAIL_HEADER_SUBJECT, originalMessage.getSubject()); } // Zeroes EMAIL_ATTACHMENT_COUNT attributes.put(EMAIL_ATTACHMENT_COUNT, "0"); // But insert correct value if attachments are present if (parser.hasAttachments()) { attributes.put(EMAIL_ATTACHMENT_COUNT, String.valueOf(parser.getAttachmentList().size())); } } catch (Exception e) { // Message is invalid or triggered an error during parsing attributes.clear(); logger.error("Could not parse the flowfile {} as an email, treating as failure", new Object[] { originalFlowFile, e }); invalidFlowFilesList.add(originalFlowFile); } } }); if (attributes.size() > 0) { FlowFile updatedFlowFile = session.putAllAttributes(originalFlowFile, attributes); logger.info("Extracted {} headers into {} file", new Object[] { attributes.size(), updatedFlowFile }); processedFlowFilesList.add(updatedFlowFile); } session.transfer(processedFlowFilesList, REL_SUCCESS); session.transfer(invalidFlowFilesList, REL_FAILURE); }
From source file:org.jkcsoft.java.mail.Emailer.java
/** * The final funnel point method that actually uses Java Mail (javax.mail.*) * API to send the message.//from ww w . j a va 2s . co m * * @throws MessagingException */ private void _sendMsg(InternetAddress[] to, InternetAddress[] bccList, InternetAddress from, String subject, String msgBody, String strMimeType) throws MessagingException { if (Strings.isEmpty(msgBody)) { msgBody = "(no email body; see subject)"; } Session session = Session.getDefaultInstance(javaMailProps, null); Message msg = new MimeMessage(session); msg.setRecipients(Message.RecipientType.TO, to); if (bccList != null) { msg.setRecipients(Message.RecipientType.BCC, bccList); } msg.setFrom(from); msg.setSubject(subject); msg.setSentDate(new Date()); msg.setContent(msgBody, strMimeType); boolean doTrySend = true; int numTries = 0; while (doTrySend) { numTries++; try { Transport.send(msg); log.info("Sent email; subject=" + subject + " to " + to[0].getAddress() + " "); doTrySend = false; } catch (MessagingException me) { log.warn("Try " + numTries + " of " + MAXTRIES + " failed:", me); if (numTries == MAXTRIES) { log.error("Failed to send email", me); throw me; } try { Thread.sleep(1000); } catch (InterruptedException e1) { LogHelper.error(this, "Retry sleep interrupted", e1); } doTrySend = numTries < MAXTRIES; } } }
From source file:com.gcrm.util.mail.MailService.java
private Session createSmtpSession(EmailSetting emailSetting) { final Properties props = new Properties(); int emailProvider = emailSetting.getEmail_provider(); String smtpUsername = null;//from www . java 2 s . co m String smtpPassword = null; switch (emailProvider) { case EmailSetting.PROVIDER_GMAIL: props.setProperty("mail.host", "smtp.gmail.com"); props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.smtp.port", "" + 587); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.smtp.starttls.enable", "true"); smtpUsername = emailSetting.getGmail_address(); smtpPassword = emailSetting.getGmail_password(); break; case EmailSetting.PROVIDER_YAHOO: props.setProperty("mail.host", "smtp.mail.yahoo.com"); props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.smtp.port", "" + 587); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.smtp.starttls.enable", "true"); smtpUsername = emailSetting.getYahoo_mail_ID(); smtpPassword = emailSetting.getYahoo_mail_password(); break; case EmailSetting.PROVIDER_OTHER: props.setProperty("mail.host", emailSetting.getSmtp_server()); props.setProperty("mail.smtp.auth", String.valueOf(emailSetting.isSmtp_authentication())); props.setProperty("mail.smtp.port", "" + emailSetting.getSmtp_port()); smtpUsername = emailSetting.getSmtp_username(); smtpPassword = emailSetting.getSmtp_password(); switch (emailSetting.getSmtp_protocol()) { case EmailSetting.PROTOCOL_SSL: props.setProperty("mail.transport.protocol", "smtps"); break; case EmailSetting.PROTOCOL_TLS: props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.smtp.starttls.enable", "true"); break; default: props.setProperty("mail.transport.protocol", "smtp"); break; } break; } final String userName = smtpUsername; final String password = smtpPassword; return Session.getDefaultInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password); } }); }
From source file:app.logica.gestores.GestorEmail.java
/** * Create a MimeMessage using the parameters provided. * * @param to// w w w. j a v a 2 s .c om * Email address of the receiver. * @param from * Email address of the sender, the mailbox account. * @param subject * Subject of the email. * @param bodyText * Body text of the email. * @param file * Path to the file to be attached. * @return MimeMessage to be used to send email. * @throws MessagingException */ private MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText, File file) 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); mimeBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(file); mimeBodyPart.setDataHandler(new DataHandler(source)); mimeBodyPart.setFileName(file.getName()); multipart.addBodyPart(mimeBodyPart); email.setContent(multipart); return email; }
From source file:gmailclientfx.core.GmailClient.java
public static MimeMessage getMimeMessage(Gmail service, String userId, String messageId) throws IOException, MessagingException { com.google.api.services.gmail.model.Message message = service.users().messages().get(userId, messageId) .setFormat("raw").execute(); byte[] emailBytes = Base64.decodeBase64(message.getRaw()); Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage email = new MimeMessage(session, new ByteArrayInputStream(emailBytes)); return email; }
From source file:org.wso2.carbon.registry.es.utils.EmailUtil.java
/** * This method read e-mails from Gmail inbox and find whether the notification of particular type is found. * * @param notificationType Notification types supported by publisher and store. * @return whether email is found for particular type. * @throws Exception//from w w w .j a v a2s .co m */ public static boolean readGmailInboxForNotification(String notificationType) throws Exception { boolean isNotificationMailAvailable = false; long waitTime = 10000; Properties props = new Properties(); props.load(new FileInputStream(new File(TestConfigurationProvider.getResourceLocation("GREG") + File.separator + "axis2" + File.separator + "smtp.properties"))); Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("smtp.gmail.com", emailAddress, java.nio.CharBuffer.wrap(emailPassword).toString()); Folder inbox = store.getFolder("inbox"); inbox.open(Folder.READ_WRITE); Thread.sleep(waitTime); long startTime = System.currentTimeMillis(); long endTime = 0; int count = 1; while (endTime - startTime < 180000 && !isNotificationMailAvailable) { Message[] messages = inbox.getMessages(); for (Message message : messages) { if (!message.isExpunged()) { try { log.info("Mail Subject:- " + message.getSubject()); if (message.getSubject().contains(notificationType)) { isNotificationMailAvailable = true; } // Optional : deleting the mail message.setFlag(Flags.Flag.DELETED, true); } catch (MessageRemovedException e) { log.error("Could not read the message subject. Message is removed from inbox"); } } } endTime = System.currentTimeMillis(); Thread.sleep(waitTime); endTime += count * waitTime; count++; } inbox.close(true); store.close(); return isNotificationMailAvailable; }
From source file:javamailclient.GmailAPI.java
/** * Create a MimeMessage using the parameters provided. * * @param to Email address of the receiver. * @param from Email address of the sender, the mailbox account. * @param subject Subject of the email.// ww w .j a va 2 s . co m * @param bodyText Body text of the email. * @return MimeMessage to be used to send email. * @throws MessagingException */ public static MimeMessage createEmail(String to, String from, String subject, String bodyText) throws MessagingException { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage email = new MimeMessage(session); InternetAddress tAddress = new InternetAddress(to); InternetAddress fAddress = new InternetAddress(from); email.setFrom(new InternetAddress(from)); email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to)); email.setSubject(subject); email.setText(bodyText); return email; }
From source file:org.apache.lens.server.query.QueryEndNotifier.java
/** Send mail. * * @param host the host * @param port the port * @param email the email * @param mailSmtpTimeout the mail smtp timeout * @param mailSmtpConnectionTimeout the mail smtp connection timeout */ public static void sendMail(String host, String port, Email email, int mailSmtpTimeout, int mailSmtpConnectionTimeout) throws Exception { Properties props = System.getProperties(); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); props.put("mail.smtp.timeout", mailSmtpTimeout); props.put("mail.smtp.connectiontimeout", mailSmtpConnectionTimeout); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(email.getFrom())); for (String recipient : email.getTo().trim().split("\\s*,\\s*")) { message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient)); }/* ww w .jav a 2 s .c o m*/ if (email.getCc() != null && email.getCc().length() > 0) { for (String recipient : email.getCc().trim().split("\\s*,\\s*")) { message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(recipient)); } } message.setSubject(email.getSubject()); message.setSentDate(new Date()); MimeBodyPart messagePart = new MimeBodyPart(); messagePart.setText(email.getMessage()); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messagePart); message.setContent(multipart); Transport.send(message); }
From source file:com.aurel.track.util.emailHandling.MailReader.java
public synchronized static String verifyMailSetting(String protocol, String server, int securityConnection, int port, String user, String password) { LOGGER.debug(" Verify mail setting: " + protocol + ":" + server + ":" + port + "," + user + "..."); try {/*from ww w . ja v a 2 s .c o m*/ // create session instance Properties props = System.getProperties(); updateSecurityProps(protocol, server, securityConnection, props); Session session = Session.getDefaultInstance(props, null); // instantiate POP3-store and connect to server store = session.getStore(protocol); store.connect(server, port, user, password); store.close(); } catch (Exception ex) { LOGGER.warn("Incoming e-mail settings don't work: " + protocol + ":" + server + ":" + port + ", user " + user + " - " + ex.getMessage()); if (LOGGER.isDebugEnabled()) { LOGGER.error(ExceptionUtils.getStackTrace(ex)); } return ex.getLocalizedMessage() == null ? ex.getClass().getName() : ex.getLocalizedMessage(); } LOGGER.debug("Mail setting: " + protocol + ":" + server + ":" + port + "," + user + " valid!"); return null; }
From source file:rescustomerservices.GmailQuickstart.java
/** * Create a MimeMessage using the parameters provided. * * @param to Email address of the receiver. * @param from Email address of the sender, the mailbox account. * @param subject Subject of the email.//from w w w . jav a 2s . co m * @param bodyText Body text of the email. * @param fileDir Path to the directory containing attachment. * @param filename Name of file to be attached. * @return MimeMessage to be used to send email. * @throws MessagingException */ public MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText, String fileDir, String filename) throws MessagingException, IOException { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage email = new MimeMessage(session); InternetAddress tAddress = new InternetAddress(to); InternetAddress fAddress = new InternetAddress(from); email.setFrom(fAddress); email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress); email.setSubject(subject); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(bodyText, "text/plain"); mimeBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\""); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); mimeBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(fileDir + filename); mimeBodyPart.setDataHandler(new DataHandler(source)); mimeBodyPart.setFileName(filename); String contentType = Files.probeContentType(FileSystems.getDefault().getPath(fileDir, filename)); mimeBodyPart.setHeader("Content-Type", contentType + "; name=\"" + filename + "\""); mimeBodyPart.setHeader("Content-Transfer-Encoding", "base64"); multipart.addBodyPart(mimeBodyPart); email.setContent(multipart); return email; }