List of usage examples for javax.mail Session getDefaultInstance
public static Session getDefaultInstance(Properties props)
From source file:jp.co.acroquest.endosnipe.collector.notification.smtp.SMTPSender.java
/** * ??/*from w w w . java2s .c o m*/ * * @param config javelin.properties??? * @param entry ?? * @return ??? * @throws MessagingException ?????? */ protected MimeMessage createMailMessage(final DataCollectorConfig config, final AlarmEntry entry) throws MessagingException { // JavaMail??? Properties props = System.getProperties(); String smtpServer = this.config_.getSmtpServer(); if (smtpServer == null || smtpServer.length() == 0) { LOGGER.log(LogMessageCodes.SMTP_SERVER_NOT_SPECIFIED); String detailMessageKey = "collector.notification.smtp.SMTPSender.SMTPNotSpecified"; String messageDetail = CommunicatorMessages.getMessage(detailMessageKey); throw new MessagingException(messageDetail); } props.setProperty(SMTP_HOST_KEY, smtpServer); int smtpPort = config.getSmtpPort(); props.setProperty(SMTP_PORT_KEY, String.valueOf(smtpPort)); // ??????? Session session = null; if (authenticator_ == null) { // ????? session = Session.getDefaultInstance(props); } else { // ??? props.setProperty(SMTP_AUTH_KEY, "true"); session = Session.getDefaultInstance(props, authenticator_); } // MIME?? MimeMessage message = new MimeMessage(session); // ?? // : Date date = new Date(); String encoding = this.config_.getSmtpEncoding(); message.setHeader("X-Mailer", X_MAILER); message.setHeader("Content-Type", "text/plain; charset=\"" + encoding + "\""); message.setSentDate(date); // :from String from = this.config_.getSmtpFrom(); InternetAddress fromAddr = new InternetAddress(from); message.setFrom(fromAddr); // :to String[] recipients = this.config_.getSmtpTo().split(","); for (String toStr : recipients) { InternetAddress toAddr = new InternetAddress(toStr); message.addRecipient(Message.RecipientType.TO, toAddr); } // :body, subject String subject; String body; subject = createSubject(entry, date); try { body = createBody(entry, date); } catch (IOException ex) { LOGGER.log(LogMessageCodes.FAIL_READ_MAIL_TEMPLATE, ""); body = createDefaultBody(entry, date); } message.setSubject(subject, encoding); message.setText(body, encoding); return message; }
From source file:org.apache.james.protocols.smtp.netty.NettyStartTlsSMTPServerTest.java
@Test public void startTlsShouldWorkWhenUsingJavamail() throws Exception { TestMessageHook hook = new TestMessageHook(); server = createServer(createProtocol(Optional.<ProtocolHandler>of(hook)), Encryption.createStartTls(BogusSslContextFactory.getServerContext())); server.bind();// ww w. ja v a 2 s . c o m SMTPTransport transport = null; try { InetSocketAddress bindedAddress = new ProtocolServerUtils(server).retrieveBindedAddress(); Properties mailProps = new Properties(); mailProps.put("mail.smtp.from", "test@localhost"); mailProps.put("mail.smtp.host", bindedAddress.getHostName()); mailProps.put("mail.smtp.port", bindedAddress.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); InternetAddress[] rcpts = new InternetAddress[] { new InternetAddress("valid@localhost") }; MimeMessage message = new MimeMessage(mailSession); message.setFrom(new InternetAddress("test@localhost")); message.setRecipients(Message.RecipientType.TO, rcpts); message.setSubject("Testmail", "UTF-8"); message.setText("Test....."); transport = (SMTPTransport) mailSession.getTransport("smtps"); transport.connect(new Socket(bindedAddress.getHostName(), bindedAddress.getPort())); transport.sendMessage(message, rcpts); assertThat(hook.getQueued()).hasSize(1); } finally { if (transport != null) { transport.close(); } } }
From source file:org.apache.james.transport.mailets.StripAttachmentTest.java
@Test public void testToAndFromAttributes() throws MessagingException, IOException { Mailet strip = new StripAttachment(); FakeMailetConfig mci = new FakeMailetConfig("Test", FakeMailContext.defaultContext()); mci.setProperty("attribute", "my.attribute"); mci.setProperty("remove", "all"); mci.setProperty("notpattern", ".*\\.tmp.*"); strip.init(mci);/*w ww . j a va 2 s. c o m*/ Mailet recover = new RecoverAttachment(); FakeMailetConfig mci2 = new FakeMailetConfig("Test", FakeMailContext.defaultContext()); mci2.setProperty("attribute", "my.attribute"); recover.init(mci2); Mailet onlyText = new OnlyText(); onlyText.init(new FakeMailetConfig("Test", FakeMailContext.defaultContext())); 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("=?iso-8859-15?Q?=E9_++++Pubblicit=E0_=E9_vietata____Milano9052.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(); Assert.assertTrue(mail.getMessage().getContent() instanceof MimeMultipart); Assert.assertEquals(3, ((MimeMultipart) mail.getMessage().getContent()).getCount()); strip.service(mail); Assert.assertTrue(mail.getMessage().getContent() instanceof MimeMultipart); Assert.assertEquals(1, ((MimeMultipart) mail.getMessage().getContent()).getCount()); onlyText.service(mail); Assert.assertFalse(mail.getMessage().getContent() instanceof MimeMultipart); Assert.assertEquals("simple text", mail.getMessage().getContent()); // prova per caricare il mime message da input stream che altrimenti // javamail si comporta differentemente. String mimeSource = "Message-ID: <26194423.21197328775426.JavaMail.bago@bagovista>\r\nSubject: test\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=us-ascii\r\nContent-Transfer-Encoding: 7bit\r\n\r\nsimple text"; MimeMessage mmNew = new MimeMessage(Session.getDefaultInstance(new Properties()), new ByteArrayInputStream(mimeSource.getBytes("UTF-8"))); mmNew.writeTo(System.out); mail.setMessage(mmNew); recover.service(mail); Assert.assertTrue(mail.getMessage().getContent() instanceof MimeMultipart); Assert.assertEquals(2, ((MimeMultipart) mail.getMessage().getContent()).getCount()); Object actual = ((MimeMultipart) mail.getMessage().getContent()).getBodyPart(1).getContent(); if (actual instanceof ByteArrayInputStream) { Assert.assertEquals(body2, toString((ByteArrayInputStream) actual)); } else { Assert.assertEquals(body2, actual); } }
From source file:org.fao.geonet.services.register.SelfRegister.java
/** * Send an email./*from ww w . jav a2 s . c o m*/ * * @param host * @param port * @param subject * @param from * @param to * @param content * @return */ boolean sendMail(String host, int port, String subject, String from, String to, String content) { boolean isSendout = false; Properties props = new Properties(); props.put("mail.transport.protocol", PROTOCOL); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); props.put("mail.smtp.auth", "false"); Session mailSession = Session.getDefaultInstance(props); try { Message msg = new MimeMessage(mailSession); msg.setFrom(new InternetAddress(from)); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); msg.setSentDate(new Date()); msg.setSubject(subject); // Add content message msg.setText(content); Transport.send(msg); isSendout = true; } catch (AddressException e) { isSendout = false; e.printStackTrace(); } catch (MessagingException e) { isSendout = false; e.printStackTrace(); } return isSendout; }
From source file:org.collectionspace.chain.csp.persistence.file.TestGeneral.java
/** * Sets up and sends email message providing you have set up the email address to send to *///ww w. j ava2 s. c om @Test public void testEmail() { Boolean doIreallyWantToSpam = false; // set to true when you have configured the email addresses /* please personalises these emails before sending - I don't want your spam. */ String from = "admin@collectionspace.org"; String[] recipients = { "" }; String SMTP_HOST_NAME = "localhost"; String SMTP_PORT = "25"; String message = "Hi, Test Message Contents"; String subject = "A test from collectionspace test suite"; String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); //REM - Replace. This is pre-JDK 1.4 code, from the days when JSSE was a separate download. Fix the imports so they refer to the classes in javax.net.ssl If you really want to get hold of a specific instance, you can use Security.getProvider(name). You'll find the appropriate names in the providers documentation. boolean debug = true; Properties props = new Properties(); props.put("mail.smtp.host", SMTP_HOST_NAME); //props.put("mail.smtp.auth", "true"); props.put("mail.smtp.auth", "false"); props.put("mail.debug", "true"); props.put("mail.smtp.port", SMTP_PORT); props.put("mail.smtp.socketFactory.port", SMTP_PORT); props.put("mail.smtp.socketFactory.class", SSL_FACTORY); props.put("mail.smtp.socketFactory.fallback", "false"); Session session = Session.getDefaultInstance(props); session.setDebug(debug); if (doIreallyWantToSpam) { Message msg = new MimeMessage(session); InternetAddress addressFrom; try { addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); InternetAddress[] addressTo = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { addressTo[i] = new InternetAddress(recipients[i]); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Setting the Subject and Content Type msg.setSubject(subject); msg.setContent(message, "text/plain"); if (doIreallyWantToSpam) { Transport.send(msg); assertTrue(doIreallyWantToSpam); } } catch (AddressException e) { log.debug(e.getMessage()); assertTrue(false); } catch (MessagingException e) { log.debug(e.getMessage()); assertTrue(false); } } //assertTrue(doIreallyWantToSpam); }
From source file:org.alfresco.repo.imap.ImapMessageTest.java
public void testMessageModifiedBetweenReads() throws Exception { // Get test message UID final Long uid = getMessageUid(folder, 1); // Get unmodified message BODY body = getMessageBody(folder, uid); // Parse the multipart MIME message MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()), new BufferedInputStream(body.getByteArrayInputStream())); // Reading first part - should be successful MimeMultipart content = (MimeMultipart) message.getContent(); assertNotNull(content.getBodyPart(0).getContent()); // Reading second part - should be successful assertNotNull(content.getBodyPart(1).getContent()); // Modify message. The size of letter describing the node may change // These changes should be committed because it should be visible from client NodeRef contentNode = findNode(companyHomePathInStore + TEST_FILE); UserTransaction txn = transactionService.getUserTransaction(); txn.begin();/*w ww. ja v a 2 s . c om*/ ContentWriter writer = fileFolderService.getWriter(contentNode); StringBuffer sb = new StringBuffer(); for (int i = 0; i < 2000; i++) { sb.append("test string"); } writer.putContent(sb.toString()); txn.commit(); // Read updated message part BODY bodyNew = getMessageBody(folder, uid); // The body should be updated assertFalse(Arrays.equals(bodyNew.getByteArray().getBytes(), body.getByteArray().getBytes())); // Parse the multipart MIME message message = new MimeMessage(Session.getDefaultInstance(new Properties()), new BufferedInputStream(bodyNew.getByteArrayInputStream())); // Reading first part - should be successful content = (MimeMultipart) message.getContent(); assertNotNull(content.getBodyPart(0).getContent()); // Reading second part - should be successful assertNotNull(content.getBodyPart(1).getContent()); }
From source file:org.apache.jmeter.assertions.SMIMEAssertion.java
/** * extracts a MIME message from the SampleResult */// w ww .j av a2 s. c om private static MimeMessage getMessageFromResponse(SampleResult response, int messageNumber) throws MessagingException { SampleResult[] subResults = response.getSubResults(); if (messageNumber >= subResults.length || messageNumber < 0) { throw new MessagingException("Message number not present in results: " + messageNumber); } final SampleResult sampleResult = subResults[messageNumber]; if (log.isDebugEnabled()) { log.debug("Bytes: " + sampleResult.getBytes() + " CT: " + sampleResult.getContentType()); } byte[] data = sampleResult.getResponseData(); Session session = Session.getDefaultInstance(new Properties()); MimeMessage msg = new MimeMessage(session, new ByteArrayInputStream(data)); log.debug("msg.getSize() = " + msg.getSize()); return msg; }
From source file:com.blackducksoftware.tools.commonframework.standard.email.CFEmailNotifier.java
/** * This is the actual java mail execution. * * @param notification/*w ww .ja v a 2 s . c o m*/ */ private void send(EmailTemplate notification) { String from = notification.getFrom(); String to = notification.getTo(); String subject = notification.getSubject(); String style = notification.getStyle(); // body of the email is set and all substitutions of variables are made String body = notification.getBody(); // Get system properties Properties props = System.getProperties(); // Setup mail server props.put("mail.smtp.host", smtpHost); props.put("mail.smtps.port", smtpPort); props.put("mail.smtps.auth", smtpUseAuth ? "true" : "false"); // if (smtpUseAuth) { // // props.setProperty("mail.smtp.auth", smtpUseAuth + ""); // props.setProperty("mail.username", smtpUsername); // props.setProperty("mail.password", smtpPassword); // // } // Get the default Session object. Session session = Session.getDefaultInstance(props); // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); try { // Set the RFC 822 "From" header field using the // value of the InternetAddress.getLocalAddress method. message.setFrom(new InternetAddress(from)); // Add the given addresses to the specified recipient type. message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); // Set the "Subject" header field. message.setSubject(subject); // Sets the given String as this part's content, // with a MIME type of "text/html". message.setContent(style + body, "text/html"); if (smtpUseAuth) { // Send message Transport tr = session.getTransport(smtpProtocol); tr.connect(smtpHost, smtpPort, smtpUsername, smtpPassword); message.saveChanges(); tr.sendMessage(message, message.getAllRecipients()); tr.close(); } else { Transport.send(message); } } catch (AddressException e) { log.error("Email Exception: Cannot connect to email host: " + smtpHost, e); } catch (MessagingException e) { log.error("Email Exception: Cannot send email message", e); } }
From source file:de.helmholtz_muenchen.ibis.utils.abstractNodes.HTExecutorNode.HTExecutorNodeModel.java
private void sendMail(String content) { Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", emailhost); Session session = Session.getDefaultInstance(properties); try {//w w w . j a v a 2 s.c o m MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(emailsender)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(email)); message.setSubject(HEADER); message.setText(content); Transport.send(message); } catch (MessagingException mex) { mex.printStackTrace(); } }
From source file:com.agiletec.plugins.jpwebmail.aps.system.services.webmail.WebMailManager.java
/** * Prepara la Session per l'invio della mail, inoltre effettua l'handshake SSL con l'host di destinazione quando richiesto. * @return La Session pronta per l'uso.// w w w. j a v a 2s . c o m */ protected Session createSession(boolean sentMail, String username, String password) throws ApsSystemException { //Properties properties = System.getProperties(); Properties properties = new Properties(); WebMailConfig config = this.getConfig(); String imapProtocol = config.getImapProtocol(); String host = config.getImapHost(); Integer port = config.getImapPort(); if (null != imapProtocol && imapProtocol.trim().length() > 0) { properties.setProperty("mail.store.protocol", imapProtocol); } else { throw new ApsSystemException("IMAP Protocoll missing"); } if (null != host && host.trim().length() > 0) { properties.setProperty("mail.imap.host", host); } else { throw new ApsSystemException("IMAP host missing"); } if (null != port && port.intValue() > 0) { properties.setProperty("mail.imap.port", port.toString()); } else { throw new ApsSystemException("IMAP port missing"); } // analizza il certificato dell'host. Se l'handshake gi stato effettuato ritorna immediatamente this.getCertificateHandler().aquireCertificate(host, port.intValue(), imapProtocol, config); // verifica se si possa procedere in sicurezza con la connessione all'host if (!this.getCertificateHandler().proceedWithConnection()) { _logger.info("Connection to host '" + host + "' not trusted"); //ApsSystemUtils.getLogger().info("Connection to host '" + host + "' not trusted"); } else { _logger.info("Connection to host '" + host + "' trusted"); //ApsSystemUtils.getLogger().info("Connection to host '" + host + "' trusted"); } properties.setProperty("mail.imap.timeout", "5000"); if (imapProtocol.equalsIgnoreCase("imaps")) { properties.setProperty("mail.imap.ssl.protocols", "SSL"); properties.setProperty("mail.imap.starttls.enable", "true"); } if (config.getLocalhost() != null && config.getLocalhost().trim().length() > 0) { properties.put("mail.smtp.localhost", config.getLocalhost()); } //SMTP START properties.put("mail.smtp.host", config.getSmtpHost()); Integer smtpPort = config.getSmtpPort(); if (smtpPort != null && smtpPort.intValue() > 0) { properties.put("mail.smtp.port", smtpPort.toString()); } int timeout = DEFAULT_SMTP_TIMEOUT; Integer timeoutParam = null;//config.getSmtpTimeout(); if (null != timeoutParam && timeoutParam.intValue() != 0) { timeout = timeoutParam; } properties.put("mail.smtp.connectiontimeout", timeout); properties.put("mail.smtp.timeout", timeout); Session session = null; if (sentMail) { properties.put("mail.smtp.auth", "true"); switch (config.getSmtpProtocol()) { case WebMailConfig.PROTO_SSL: properties.put("mail.smtp.socketFactory.port", smtpPort.toString()); properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.transport.protocol", "smtps"); break; case WebMailConfig.PROTO_TLS: properties.put("mail.smtp.starttls.enable", "true"); break; case WebMailConfig.PROTO_STD: //do nothing just use previous properties WITH the authenticator break; } Authenticator auth = new SMTPAuthenticator(username, password); session = Session.getInstance(properties, auth); } else { session = Session.getDefaultInstance(properties); } return session; }