List of usage examples for javax.mail Session getDefaultInstance
public static Session getDefaultInstance(Properties props)
From source file:com.garethahealy.elasticpostman.scraper.entities.EmailContent.java
public void parse() throws Exception { Session session = Session.getDefaultInstance(new Properties()); MimeMessage message = MimeMessageUtils.createMimeMessage(session, raw); MimeMessageParser mimeMessageParser = new MimeMessageParser(message); MimeMessageParser parsed = mimeMessageParser.parse(); this.from = parsed.getFrom(); this.subject = parsed.getSubject(); this.content = parsed.getPlainContent(); this.contentIds = parsed.getContentIds(); this.sentDate = new DateTime(parsed.getMimeMessage().getSentDate()); this.headers = new HashMap<String, String>(); @SuppressWarnings("unchecked") EnumerationIterator it = new EnumerationIterator(parsed.getMimeMessage().getAllHeaders()); while (it.hasNext()) { Object current = it.next(); if (current instanceof Header) { Header header = (Header) current; if (includeHeader(header.getName())) { headers.put(header.getName(), sanatizeValue(header.getName(), header.getValue())); }//ww w . ja v a 2 s .co m } } }
From source file:info.debatty.java.datasets.enron.Email.java
Email(final String raw, final String mailbox) throws MessagingException, Exception { this.raw = raw; String[] strings = mailbox.split(File.separator, 2); this.user = strings[0]; this.mailbox = strings[1]; Session s = Session.getDefaultInstance(new Properties()); InputStream is = new ByteArrayInputStream(raw.getBytes()); MimeMessage message = new MimeMessage(s, is); MimeMessageParser parser = new MimeMessageParser(message); from = parser.getFrom();/*from w w w .j ava 2 s. c o m*/ to = addressToString(parser.getTo()); cc = addressToString(parser.getCc()); bcc = addressToString(parser.getBcc()); subject = parser.getSubject(); content = parser.getPlainContent(); message_id = parser.getMimeMessage().getMessageID(); }
From source file:mailhost.StartApp.java
public void sendEmail(String to, String subject, String body) throws UnsupportedEncodingException, MessagingException { System.out.println(String.format("Sending notification email recipients " + "to " + to + " subject " + subject + "host " + mailhost)); if (StringUtils.isBlank(to)) throw new IllegalArgumentException("The email request should have at least one recipient"); Properties properties = new Properties(); properties.setProperty("mail.smtp.host", mailhost); Session session = Session.getDefaultInstance(properties); Address[] a = new InternetAddress[1]; a[0] = new InternetAddress("test@matson.com"); MimeMessage message = new MimeMessage(session); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.addFrom(a);/*from ww w . j av a 2 s . c o m*/ message.setSubject(subject); message.setContent(body, "text/html; charset=utf-8"); //message.setText(body); // Send message Transport.send(message); System.out.println("Email sent."); }
From source file:org.openiam.idm.srvc.msg.service.MailSenderClient.java
public void send(Message msg) { Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); properties.setProperty("mail.transport.protocol", "smtp"); if (username != null && !username.isEmpty()) { properties.setProperty("mail.user", username); properties.setProperty("mail.password", password); }//from ww w . j a va 2 s.c om if (port != null && !port.isEmpty()) { properties.setProperty("mail.smtp.port", port); } Session session = Session.getDefaultInstance(properties); MimeMessage message = new MimeMessage(session); try { message.setFrom(msg.getFrom()); if (msg.getTo().size() > 1) { List<InternetAddress> addresses = msg.getTo(); message.addRecipients(TO, addresses.toArray(new Address[addresses.size()])); } else { message.addRecipient(TO, msg.getTo().get(0)); } if (msg.getBcc() != null && msg.getBcc().size() != 0) { if (msg.getTo().size() > 1) { List<InternetAddress> addresses = msg.getBcc(); message.addRecipients(BCC, addresses.toArray(new Address[addresses.size()])); } else { message.addRecipient(TO, msg.getBcc().get(0)); } } if (msg.getCc() != null && msg.getCc().size() > 0) { if (msg.getCc().size() > 1) { List<InternetAddress> addresses = msg.getCc(); message.addRecipients(CC, addresses.toArray(new Address[addresses.size()])); } else { message.addRecipient(CC, msg.getCc().get(0)); } } message.setSubject(msg.getSubject(), "UTF-8"); MimeBodyPart mbp1 = new MimeBodyPart(); // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); if (msg.getBodyType() == Message.BodyType.HTML_TEXT) { mbp1.setContent(msg.getBody(), "text/html"); } else { mbp1.setText(msg.getBody(), "UTF-8"); } if (port != null && !port.isEmpty()) { properties.setProperty("mail.smtp.port", port); } mp.addBodyPart(mbp1); if (msg.getAttachments().size() > 0) { for (String fileName : msg.getAttachments()) { // create the second message part MimeBodyPart mbpFile = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(fileName); mbpFile.setDataHandler(new DataHandler(fds)); mbpFile.setFileName(fds.getName()); mp.addBodyPart(mbpFile); } } // add the Multipart to the message message.setContent(mp); if (username != null && !username.isEmpty()) { properties.setProperty("mail.user", username); properties.setProperty("mail.password", password); properties.put("mail.smtp.auth", auth); properties.put("mail.smtp.starttls.enable", starttls); Transport mailTransport = session.getTransport(); mailTransport.connect(host, username, password); mailTransport.sendMessage(message, message.getAllRecipients()); } else { Transport.send(message); log.debug("Message successfully sent."); } } catch (Throwable e) { log.error("Exception while sending mail", e); } }
From source file:ch.unibas.fittingwizard.application.tools.Notifications.java
private void sendMailGaussian(boolean isLogValid) { try {//from w ww. j a v a 2 s . com Email email = new SimpleEmail(); email.setMailSession(Session.getDefaultInstance(props)); email.setSubject("Gaussian calculation finished"); email.setMsg("Gaussian calculation finished. Log file validation returned: " + isLogValid); email.setFrom(getSender().trim()); email.addTo(getRecipient().trim()); email.send(); } catch (EmailException e) { throw new RuntimeException("Could not send notification.", e); } }
From source file:net.orpiske.dcd.collector.dataset.impl.MBoxDataSet.java
/** * Constructor//from www .ja v a2 s . c om * @param file A File pointer to the MBox file * @throws MessagingException if unable to read or process the file */ public MBoxDataSet(final File file) throws MessagingException { logger.debug("Creating a new data set from file " + file.getPath()); Properties properties = new Properties(); Session session; properties.setProperty("mail.store.protocol", "mstor"); properties.setProperty("mstor.mbox.metadataStrategy", "none"); properties.setProperty("mstor.mbox.cacheBuffers", "disabled"); properties.setProperty("mstor.mbox.bufferStrategy", "mapped"); properties.setProperty("mstor.metadata", "disabled"); properties.setProperty("mstor.mozillaCompatibility", "enabled"); session = Session.getDefaultInstance(properties); store = session.getStore(new URLName("mstor:" + file.getPath())); store.connect(); loadMessages(); }
From source file:org.apache.james.transport.mailets.StripAttachmentTest.java
@Test public void testSimpleAttachment() throws MessagingException, IOException { Mailet mailet = initMailet();// www.jav a 2s .c o m MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties())); MimeMultipart mm = new MimeMultipart(); MimeBodyPart mp = new MimeBodyPart(); mp.setText("simple text"); mm.addBodyPart(mp); String body = "\u0023\u00A4\u00E3\u00E0\u00E9"; MimeBodyPart mp2 = new MimeBodyPart(new ByteArrayInputStream( ("Content-Transfer-Encoding: 8bit\r\nContent-Type: application/octet-stream; charset=utf-8\r\n\r\n" + body).getBytes("UTF-8"))); mp2.setDisposition("attachment"); mp2.setFileName("10.tmp"); mm.addBodyPart(mp2); String body2 = "\u0014\u00A3\u00E1\u00E2\u00E4"; MimeBodyPart mp3 = new MimeBodyPart(new ByteArrayInputStream( ("Content-Transfer-Encoding: 8bit\r\nContent-Type: application/octet-stream; charset=utf-8\r\n\r\n" + body2).getBytes("UTF-8"))); mp3.setDisposition("attachment"); mp3.setFileName("temp.zip"); mm.addBodyPart(mp3); message.setSubject("test"); message.setContent(mm); message.saveChanges(); Mail mail = FakeMail.builder().mimeMessage(message).build(); mailet.service(mail); ByteArrayOutputStream rawMessage = new ByteArrayOutputStream(); mail.getMessage().writeTo(rawMessage, new String[] { "Bcc", "Content-Length", "Message-ID" }); @SuppressWarnings("unchecked") Collection<String> c = (Collection<String>) mail .getAttribute(StripAttachment.SAVED_ATTACHMENTS_ATTRIBUTE_KEY); Assert.assertNotNull(c); Assert.assertEquals(1, c.size()); String name = c.iterator().next(); File f = new File("./" + name); try { InputStream is = new FileInputStream(f); String savedFile = toString(is); is.close(); Assert.assertEquals(body, savedFile); } finally { FileUtils.deleteQuietly(f); } }
From source file:com.github.sleroy.junit.mail.server.test.MailSender.java
/** * Send mail./*w ww . ja va 2s. c om*/ * * @param from * Sender's email ID needs to be mentioned * @param to * Recipient's email ID needs to be mentioned. * @param subject * the subject * @throws MessagingException */ public void sendMail(String from, String to, String subject, String body) throws MessagingException { // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", host); properties.setProperty("mail.smtp.port", Integer.toString(port)); // Get the default Session object. Session session = Session.getDefaultInstance(properties); Transport transport = null; try { transport = session.getTransport(); // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject(subject); // Now set the actual message message.setText(body); // Send message transport.send(message); System.out.println("Sent message successfully...."); } finally { if (transport != null) { transport.close(); } } }
From source file:com.autentia.tnt.mail.DefaultMailService.java
/** * This method is used by Spring Framework *///from w w w .j ava2 s .com private void init() { try { properties.put("mail.smtp.host", configurationUtil.getMailHost()); properties.put("mail.smtp.port", Integer.parseInt(configurationUtil.getMailPort())); properties.put("mail.smtp.user", configurationUtil.getMailUsername()); properties.put("mail.smtp.auth", configurationUtil.getMailRequiresAuth()); session = Session.getDefaultInstance(properties); } catch (Exception e) { log.warn("The smtp server is not configured: " + e); } }
From source file:org.apache.oodt.cas.crawl.action.EmailNotification.java
@Override public boolean performAction(File product, Metadata metadata) throws CrawlerActionException { try {//from w ww . j a va2 s.c o m Properties props = new Properties(); props.put("mail.host", this.mailHost); props.put("mail.transport.protocol", "smtp"); props.put("mail.from", this.sender); Session session = Session.getDefaultInstance(props); Message msg = new MimeMessage(session); msg.setSubject(PathUtils.doDynamicReplacement(subject, metadata)); msg.setText(new String(PathUtils.doDynamicReplacement(message, metadata).getBytes())); for (String recipient : recipients) { try { msg.addRecipient(Message.RecipientType.TO, new InternetAddress( PathUtils.replaceEnvVariables(recipient.trim(), metadata), ignoreInvalidAddresses)); LOG.fine("Recipient: " + PathUtils.replaceEnvVariables(recipient.trim(), metadata)); } catch (AddressException ae) { LOG.fine("Recipient: " + PathUtils.replaceEnvVariables(recipient.trim(), metadata)); LOG.warning(ae.getMessage()); } } LOG.fine("Subject: " + msg.getSubject()); LOG.fine("Message: " + new String(PathUtils.doDynamicReplacement(message, metadata).getBytes())); Transport.send(msg); return true; } catch (Exception e) { LOG.severe(e.getMessage()); return false; } }