List of usage examples for javax.mail Session getDefaultInstance
public static Session getDefaultInstance(Properties props)
From source file:fr.aliacom.obm.common.calendar.MailSendTest.java
private String writeEventMail(EventMail eventMail) throws IOException, MessagingException { MimeMessage mail = eventMail.buildMimeMail(Session.getDefaultInstance(new Properties())); ByteArrayOutputStream mailByteStream = new ByteArrayOutputStream(); mail.writeTo(mailByteStream);//from w w w .ja v a 2 s . c o m return new String(mailByteStream.toByteArray(), CharsetNames.CS_UTF8); }
From source file:org.apache.james.transport.mailets.StripAttachmentTest.java
@Test public void testSimpleAttachment2() throws MessagingException, IOException { Mailet mailet = new StripAttachment(); FakeMailetConfig mci = new FakeMailetConfig("Test", FakeMailContext.defaultContext()); mci.setProperty("directory", "./"); mci.setProperty("remove", "all"); mci.setProperty("notpattern", "^(winmail\\.dat$)"); mailet.init(mci);/*from w w w . j ava 2s . com*/ 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\n\r\n" + body).getBytes("UTF-8"))); mp2.setDisposition("attachment"); mp2.setFileName("temp.tmp"); mm.addBodyPart(mp2); String body2 = "\u0014\u00A3\u00E1\u00E2\u00E4"; MimeBodyPart mp3 = new MimeBodyPart( new ByteArrayInputStream(("Content-Transfer-Encoding: 8bit\r\n\r\n" + body2).getBytes("UTF-8"))); mp3.setDisposition("attachment"); mp3.setFileName("winmail.dat"); 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" }); // String res = rawMessage.toString(); @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.google.code.rptm.mailarchive.DefaultMailingListArchive.java
public void retrieveMessages(String mailingList, YearMonth month, MimeMessageProcessor processor, MailingListArchiveEventListener eventListener) throws MailingListArchiveException { Session session = Session.getDefaultInstance(new Properties()); try {/*from www . jav a 2 s .c o m*/ Store store = session.getStore(new URLName("mstor:" + getMboxFile(mailingList, month, eventListener))); store.connect(); try { Folder folder = store.getDefaultFolder(); folder.open(Folder.READ_ONLY); for (Message msg : folder.getMessages()) { if (!processor.processMessage((MimeMessage) msg)) { break; } } } finally { store.close(); } } catch (MessagingException ex) { throw new MailingListArchiveException("JavaMail exception: " + ex.getMessage(), ex); } catch (IOException ex) { throw new MailingListArchiveException("I/O exception: " + ex.getMessage(), ex); } }
From source file:nz.net.orcon.kanban.automation.actions.EmailReceiverAction.java
/** * @param mailStoreProtocol/* w w w .ja va 2s. c o m*/ * @param mailStoreHost * @param mailStoreUserName * @param mailStorePassword * @return */ private Session getMailStoreSession(String mailStoreProtocol, String mailStoreHost, String mailStoreUserName, String mailStorePassword) { Properties properties = new Properties(); properties.put("mail.store.protocol", mailStoreProtocol); properties.put("mail.store.host", mailStoreHost); properties.put("mail.store.username", mailStoreUserName); properties.put("mail.store.pasword", mailStorePassword); return Session.getDefaultInstance(properties); }
From source file:ru.retbansk.utils.scheduled.impl.ReadEmailAndConvertToXmlSpringImpl.java
/** * Loads email properties, reads email messages, * converts their multipart bodies into string, * send error emails if message doesn't contain valid report and at last returns a reversed Set of the Valid Reports * <p><b> deletes messages//from w w w . ja va 2 s. c o m * @see #readEmail() * @see #convertToXml(HashSet) * @see ru.retbansk.utils.scheduled.ReplyManager * @return HashSet<DayReport> of the Valid Day Reports */ @Override public HashSet<DayReport> readEmail() throws Exception { Properties prop = loadProperties(); String host = prop.getProperty("host"); String user = prop.getProperty("user"); String password = prop.getProperty("password"); path = prop.getProperty("path"); // Get system properties Properties properties = System.getProperties(); // Get the default Session object. Session session = Session.getDefaultInstance(properties); // Get a Store object that implements the specified protocol. Store store = session.getStore("pop3"); // Connect to the current host using the specified username and // password. store.connect(host, user, password); // Create a Folder object corresponding to the given name. Folder folder = store.getFolder("inbox"); // Open the Folder. folder.open(Folder.READ_WRITE); HashSet<DayReport> dayReportSet = new HashSet<DayReport>(); try { // Getting messages from the folder Message[] message = folder.getMessages(); // Reversing the order in the array with the use of Set to make the last one final Collections.reverse(Arrays.asList(message)); // Reading messages. String body; for (int i = 0; i < message.length; i++) { DayReport dayReport = null; dayReport = new DayReport(); dayReport.setPersonId(((InternetAddress) message[i].getFrom()[0]).getAddress()); Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+3")); calendar.setTime(message[i].getSentDate()); dayReport.setCalendar(calendar); dayReport.setSubject(message[i].getSubject()); List<TaskReport> reportList = null; //Release the string from email message body body = ""; Object content = message[i].getContent(); if (content instanceof java.lang.String) { body = (String) content; } else if (content instanceof Multipart) { Multipart mp = (Multipart) content; for (int j = 0; j < mp.getCount(); j++) { Part part = mp.getBodyPart(j); String disposition = part.getDisposition(); if (disposition == null) { MimeBodyPart mbp = (MimeBodyPart) part; if (mbp.isMimeType("text/plain")) { body += (String) mbp.getContent(); } } else if ((disposition != null) && (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE))) { MimeBodyPart mbp = (MimeBodyPart) part; if (mbp.isMimeType("text/plain")) { body += (String) mbp.getContent(); } } } } //Put the string (body of email message) and get list of valid reports else send error reportList = new ArrayList<TaskReport>(); reportList = giveValidReports(body, message[i].getSentDate()); //Check for valid day report. To be valid it should have size of reportList > 0. if (reportList.size() > 0) { // adding valid ones to Set dayReport.setReportList(reportList); dayReportSet.add(dayReport); } else { // This message doesn't have valid reports. Sending an error reply. logger.info("Invalid Day Report detected. Sending an error reply"); ReplyManager man = new ReplyManagerSimpleImpl(); man.sendError(dayReport); } // Delete message message[i].setFlag(Flags.Flag.DELETED, true); } } finally { // true tells the mail server to expunge deleted messages. folder.close(true); store.close(); } return dayReportSet; }
From source file:org.cern.flume.sink.mail.MailSink.java
@Override public Status process() throws EventDeliveryException { Status status = null;//from w w w .j a v a2s. com // Start transaction Channel ch = getChannel(); Transaction txn = ch.getTransaction(); txn.begin(); try { Event event = ch.take(); if (event != null) { // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", host); properties.put("mail.smtp.port", port); // Get the default Session object. Session session = Session.getDefaultInstance(properties); // Create a default MimeMessage object. MimeMessage mimeMessage = new MimeMessage(session); // Set From: header field of the header. mimeMessage.setFrom(new InternetAddress(sender)); // Set To: header field of the header. for (String recipient : recipients) { mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient)); } // Now set the subject and actual message Map<String, String> headers = event.getHeaders(); String value; String mailSubject = subject; for (String field : subjectFields) { try { if (field.equals("body")) { value = new String(event.getBody()); } else { value = new String(headers.get(field)); } } catch (NullPointerException t) { value = ""; } mailSubject = mailSubject.replace("%{" + field + "}", value); } String mailMessage = message; for (String field : messageFields) { try { if (field.equals("body")) { value = new String(event.getBody()); } else { value = new String(headers.get(field)); } } catch (NullPointerException t) { value = ""; } mailMessage = mailMessage.replace("%{" + field + "}", value); } mimeMessage.setSubject(mailSubject); mimeMessage.setText(mailMessage); // Send message Transport.send(mimeMessage); } txn.commit(); status = Status.READY; } catch (Throwable t) { txn.rollback(); logger.error("Unable to send e-mail.", t); status = Status.BACKOFF; if (t instanceof Error) { throw (Error) t; } } finally { txn.close(); } return status; }
From source file:org.apache.james.protocols.smtp.AbstractStartTlsSMTPServerTest.java
@Test public void testStartTLSWithJavamail() throws Exception { InetSocketAddress address = new InetSocketAddress("127.0.0.1", TestUtils.getFreePort()); ProtocolServer server = null;//from w w w .ja v a2s .com try { TestMessageHook hook = new TestMessageHook(); server = createServer(createProtocol(hook), address, Encryption.createStartTls(BogusSslContextFactory.getServerContext())); server.bind(); Properties mailProps = new Properties(); mailProps.put("mail.smtp.from", "test@localhost"); mailProps.put("mail.smtp.host", address.getHostName()); mailProps.put("mail.smtp.port", address.getPort()); mailProps.put("mail.smtp.socketFactory.class", BogusSSLSocketFactory.class.getName()); mailProps.put("mail.smtp.socketFactory.fallback", "false"); mailProps.put("mail.smtp.starttls.enable", "true"); Session mailSession = Session.getDefaultInstance(mailProps); MimeMessage message = new MimeMessage(mailSession); message.setFrom(new InternetAddress("test@localhost")); String[] emails = { "valid@localhost" }; Address rcpts[] = new Address[emails.length]; for (int i = 0; i < emails.length; i++) { rcpts[i] = new InternetAddress(emails[i].trim().toLowerCase()); } message.setRecipients(Message.RecipientType.TO, rcpts); message.setSubject("Testmail", "UTF-8"); message.setText("Test....."); SMTPTransport transport = (SMTPTransport) mailSession.getTransport("smtps"); transport.connect(new Socket(address.getHostName(), address.getPort())); transport.sendMessage(message, rcpts); assertEquals(1, hook.getQueued().size()); } finally { if (server != null) { server.unbind(); } } }
From source file:org.apache.mailet.base.test.MimeMessageBuilder.java
public static MimeMessage defaultMimeMessage() { return new MimeMessage(Session.getDefaultInstance(new Properties())); }
From source file:org.apache.mailet.base.test.MimeMessageBuilder.java
public static MimeMessage mimeMessageFromStream(InputStream inputStream) throws MessagingException { return new MimeMessage(Session.getDefaultInstance(new Properties()), inputStream); }
From source file:com.warsaw.data.controller.LoginController.java
private boolean sendEmail(String to) { Properties properties = System.getProperties(); // Setup mail server properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.host", HOST); properties.put("mail.smtp.user", EMAIL); properties.put("mail.smtp.password", PASS); properties.put("mail.smtp.port", "587"); properties.put("mail.smtp.auth", "true"); properties.setProperty("mail.transport.protocol", "smtp"); // Get the default Session object. Session session = Session.getDefaultInstance(properties); try {//ww w. j a v a 2s. c om Message msg = this.buildEmail(session, to); /* Transport transport = session.getTransport(); transport.send(msg);*/ Transport transport = session.getTransport("smtp"); transport.connect(HOST, EMAIL, PASS); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); } catch (Exception e) { System.out.println("Ex :" + e); return false; } return true; }