List of usage examples for javax.mail.internet InternetAddress InternetAddress
public InternetAddress(String address) throws AddressException
From source file:it.eng.spagobi.tools.scheduler.dispatcher.MailDocumentDispatchChannel.java
public boolean dispatch(BIObject document, byte[] executionOutput) { Map parametersMap;/*from w ww .ja v a 2s. co m*/ String contentType; String fileExtension; IDataStore emailDispatchDataStore; String nameSuffix; String descriptionSuffix; String containedFileName; String zipFileName; boolean reportNameInSubject; logger.debug("IN"); try { parametersMap = dispatchContext.getParametersMap(); contentType = dispatchContext.getContentType(); fileExtension = dispatchContext.getFileExtension(); emailDispatchDataStore = dispatchContext.getEmailDispatchDataStore(); nameSuffix = dispatchContext.getNameSuffix(); descriptionSuffix = dispatchContext.getDescriptionSuffix(); containedFileName = dispatchContext.getContainedFileName() != null && !dispatchContext.getContainedFileName().equals("") ? dispatchContext.getContainedFileName() : document.getName(); zipFileName = dispatchContext.getZipMailName() != null && !dispatchContext.getZipMailName().equals("") ? dispatchContext.getZipMailName() : document.getName(); reportNameInSubject = dispatchContext.isReportNameInSubject(); String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost"); String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport"); String smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL"); logger.debug(smtphost + " " + smtpport + " use SSL: " + smtpssl); //Custom Trusted Store Certificate Options String trustedStorePath = SingletonConfig.getInstance() .getConfigValue("MAIL.PROFILES.trustedStore.file"); String trustedStorePassword = SingletonConfig.getInstance() .getConfigValue("MAIL.PROFILES.trustedStore.password"); int smptPort = 25; if ((smtphost == null) || smtphost.trim().equals("")) throw new Exception("Smtp host not configured"); if ((smtpport == null) || smtpport.trim().equals("")) { throw new Exception("Smtp host not configured"); } else { smptPort = Integer.parseInt(smtpport); } String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from"); if ((from == null) || from.trim().equals("")) from = "spagobi.scheduler@eng.it"; String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user"); if ((user == null) || user.trim().equals("")) { logger.debug("Smtp user not configured"); user = null; } // throw new Exception("Smtp user not configured"); String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password"); if ((pass == null) || pass.trim().equals("")) { logger.debug("Smtp password not configured"); } // throw new Exception("Smtp password not configured"); String mailSubj = dispatchContext.getMailSubj(); mailSubj = StringUtilities.substituteParametersInString(mailSubj, parametersMap, null, false); String mailTxt = dispatchContext.getMailTxt(); String[] recipients = findRecipients(dispatchContext, document, emailDispatchDataStore); if (recipients == null || recipients.length == 0) { logger.error("No recipients found for email sending!!!"); return false; } //Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", smtphost); props.put("mail.smtp.port", Integer.toString(smptPort)); // open session Session session = null; // create autheticator object Authenticator auth = null; if (user != null) { auth = new SMTPAuthenticator(user, pass); props.put("mail.smtp.auth", "true"); //SSL Connection if (smtpssl.equals("true")) { Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); //props.put("mail.smtp.debug", "true"); props.put("mail.smtps.auth", "true"); props.put("mail.smtps.socketFactory.port", Integer.toString(smptPort)); if ((!StringUtilities.isEmpty(trustedStorePath))) { /* Dynamic configuration of trustedstore for CA * Using Custom SSLSocketFactory to inject certificates directly from specified files */ //System.setProperty("java.security.debug","certpath"); //System.setProperty("javax.net.debug","ssl "); props.put("mail.smtps.socketFactory.class", CUSTOM_SSL_FACTORY); } else { //System.setProperty("java.security.debug","certpath"); //System.setProperty("javax.net.debug","ssl "); props.put("mail.smtps.socketFactory.class", DEFAULT_SSL_FACTORY); } props.put("mail.smtp.socketFactory.fallback", "false"); } //session = Session.getDefaultInstance(props, auth); session = Session.getInstance(props, auth); //session.setDebug(true); //session.setDebugOut(null); logger.info("Session.getInstance(props, auth)"); } else { //session = Session.getDefaultInstance(props); session = Session.getInstance(props); logger.info("Session.getInstance(props)"); } // create a message Message msg = new MimeMessage(session); // set the from and to address InternetAddress 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 String subject = mailSubj; if (reportNameInSubject) { subject += " " + document.getName() + nameSuffix; } msg.setSubject(subject); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(mailTxt + "\n" + descriptionSuffix); // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message SchedulerDataSource sds = null; //if zip requested if (dispatchContext.isZipMailDocument()) { mbp2 = zipAttachment(executionOutput, containedFileName, zipFileName, nameSuffix, fileExtension); } //else else { sds = new SchedulerDataSource(executionOutput, contentType, containedFileName + nameSuffix + fileExtension); mbp2.setDataHandler(new DataHandler(sds)); mbp2.setFileName(sds.getName()); } // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); // add the Multipart to the message msg.setContent(mp); // send message if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) { //USE SSL Transport comunication with SMTPS Transport transport = session.getTransport("smtps"); transport.connect(smtphost, smptPort, user, pass); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); } else { //Use normal SMTP Transport.send(msg); } } catch (Exception e) { logger.error("Error while sending schedule result mail", e); return false; } finally { logger.debug("OUT"); } return true; }
From source file:org.ktunaxa.referral.server.command.email.SendEmailCommand.java
private void addRecipients(MimeMessage mimeMessage, Message.RecipientType recipientType, String recipients) throws MessagingException { if (null != recipients && recipients.length() > 0) { for (String part : recipients.split("[,;\\s]")) { String address = part.trim(); if (address.length() > 0) { mimeMessage.addRecipient(recipientType, new InternetAddress(address)); }/*from w w w.j av a2 s . c o m*/ } } }
From source file:gov.nih.nci.cabig.caaers.esb.client.MessageNotificationService.java
public void sendMail(String[] to, String subject, String content, String attachment) throws Exception { MimeMessage message = caaersJavaMailSender.createMimeMessage(); message.setSubject(subject);//from w w w .j av a 2 s . c om message.setFrom(new InternetAddress(configuration.get(Configuration.SYSTEM_FROM_EMAIL))); // use the true flag to indicate you need a multipart message MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(to); helper.setText(content); if (attachment != null) { File f = new File(attachment); FileSystemResource file = new FileSystemResource(f); helper.addAttachment(file.getFilename(), file); } caaersJavaMailSender.send(message); }
From source file:com.waveerp.sendMail.java
public String sendMsgWithAttach(String strSource, String strSourceDesc, String strSubject, String strMsg, String strDestination, String strDestDesc, String strPath) throws Exception { String strResult = "OK"; // Call the registry management system registrySystem rs = new registrySystem(); // Call the encryption management system desEncryption de = new desEncryption(); de.Encrypter("", ""); String strHost = rs.readRegistry("NA", "NA", "NA", "EMAILHOST"); String strPort = rs.readRegistry("NA", "NA", "NA", "EMAILPORT"); final String strUser = rs.readRegistry("NA", "NA", "NA", "EMAILUSER"); String strPass = rs.readRegistry("NA", "NA", "NA", "EMAILPASSWORD"); //Decrypt the encrypted password. final String strPass01 = de.decrypt(strPass); Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", strHost); props.put("mail.smtp.port", strPort); props.put("mail.user", strUser); props.put("mail.password", strPass01); // creates a new session with an authenticator Authenticator auth = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(strUser, strPass01); }//from w ww .j a v a2 s . c om }; Session session = Session.getInstance(props, auth); // creates a new e-mail message Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(strSource)); //InternetAddress[] toAddresses = { new InternetAddress(strDestination) }; msg.setRecipient(Message.RecipientType.TO, new InternetAddress(strDestination)); msg.setSubject(strSubject); msg.setSentDate(new Date()); // creates message part MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(strMsg, "text/html"); // creates multi-part Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // adds attachments //if (attachFiles != null && attachFiles.length > 0) { // for (String filePath : attachFiles) { // MimeBodyPart attachPart = new MimeBodyPart(); // // try { // attachPart.attachFile(filePath); // } catch (IOException ex) { // ex.printStackTrace(); // } // // multipart.addBodyPart(attachPart); // } //} String fna; String fnb; URL fileUrl; fileUrl = null; fileUrl = this.getClass().getResource("sendMail.class"); fna = fileUrl.getPath(); fna = fna.substring(0, fna.indexOf("WEB-INF")); //fnb = URLDecoder.decode( fna + TEMP_DIR + strPath ); fnb = URLDecoder.decode(fna + strPath); MimeBodyPart attachPart = new MimeBodyPart(); try { attachPart.attachFile(fnb); } catch (IOException ex) { //ex.printStackTrace(); strResult = ex.getMessage(); } multipart.addBodyPart(attachPart); // sets the multi-part as e-mail's content msg.setContent(multipart); // sends the e-mail Transport.send(msg); return strResult; }
From source file:gmailclientfx.core.GmailClient.java
public static void sendMessage(String to, String subject, String body, List<String> attachments) throws Exception { // authenticate with gmail smtp server SMTPTransport smtpTransport = connectToSmtp("smtp.gmail.com", 587, EMAIL, ACCESS_TOKEN, true); // kreiraj MimeMessage objekt MimeMessage msg = new MimeMessage(OAuth2Authenticator.getSession()); // dodaj headere msg.addHeader("Content-type", "text/HTML; charset=UTF-8"); msg.addHeader("format", "flowed"); msg.addHeader("Content-Transfer-Encoding", "8bit"); msg.setFrom(new InternetAddress(EMAIL)); msg.setRecipients(javax.mail.Message.RecipientType.CC, InternetAddress.parse(to)); msg.setSubject(subject, "UTF-8"); msg.setReplyTo(InternetAddress.parse(EMAIL, false)); // tijelo poruke BodyPart msgBodyPart = new MimeBodyPart(); msgBodyPart.setText(body);// w w w.j a v a 2s .co m Multipart multipart = new MimeMultipart(); multipart.addBodyPart(msgBodyPart); msg.setContent(multipart); // dodaj privitke if (attachments.size() > 0) { for (String attachment : attachments) { msgBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachment); msgBodyPart.setDataHandler(new DataHandler(source)); msgBodyPart.setFileName(source.getName()); multipart.addBodyPart(msgBodyPart); } msg.setContent(multipart); } smtpTransport.sendMessage(msg, InternetAddress.parse(to)); Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Poruka poslana!"); alert.setHeaderText(null); alert.setContentText("Email uspjeno poslan!"); alert.showAndWait(); }
From source file:com.zimbra.cs.mailclient.smtp.SmtpTransportTest.java
@Test(timeout = 3000) public void bracketsInMailAndRcpt() throws Exception { server = MockTcpServer.scenario().sendLine("220 test ready").recvLine() // EHLO .sendLine("250 OK").recvLine() // MAIL FROM .sendLine("250 OK").recvLine() // RCPT TO .sendLine("250 OK").recvLine() // DATA .sendLine("354 OK").swallowUntil("\r\n.\r\n").sendLine("250 OK").recvLine() // QUIT .sendLine("221 bye").build().start(PORT); Session session = JMSession.getSession(); session.getProperties().setProperty("mail.smtp.from", "<>"); Transport transport = session.getTransport("smtp"); transport.connect("localhost", PORT, null, null); String raw = "From: sender@zimbra.com\nTo: rcpt@zimbra.com\nSubject: test\n\ntest"; MimeMessage msg = new ZMimeMessage(session, new SharedByteArrayInputStream(raw.getBytes(Charsets.ISO_8859_1))); transport.sendMessage(msg, new Address[] { new InternetAddress("<rcpt@zimbra.com>") }); transport.close();/*from w w w .ja v a2 s .com*/ server.shutdown(1000); Assert.assertEquals("EHLO localhost\r\n", server.replay()); Assert.assertEquals("MAIL FROM:<>\r\n", server.replay()); Assert.assertEquals("RCPT TO:<rcpt@zimbra.com>\r\n", server.replay()); Assert.assertEquals("DATA\r\n", server.replay()); Assert.assertEquals("QUIT\r\n", server.replay()); Assert.assertNull(server.replay()); }
From source file:mitm.application.djigzo.james.matchers.HasValidPasswordTest.java
@Test public void testMultipleMatches() throws MessagingException, EncryptorException { HasValidPassword matcher = new HasValidPassword(); MockMatcherConfig matcherConfig = new MockMatcherConfig("test", "matchOnError=false", mailetContext); matcher.init(matcherConfig);/* w w w . j a v a 2s . co m*/ Mail mail = new MockMail(); MimeMessage message = new MimeMessage(MailSession.getDefaultSession()); message.setContent("test", "text/plain"); message.setFrom(new InternetAddress("123456@example.com")); message.saveChanges(); mail.setMessage(message); Collection<MailAddress> recipients = new LinkedList<MailAddress>(); recipients.add(new MailAddress("test2@example.com")); recipients.add(new MailAddress("test5@example.com")); mail.setRecipients(recipients); Collection<?> result = matcher.match(mail); assertEquals(2, result.size()); assertTrue(result.contains(new MailAddress("test2@example.com"))); assertTrue(result.contains(new MailAddress("test5@example.com"))); DjigzoMailAttributes attributes = new DjigzoMailAttributesImpl(mail); Passwords passwords = attributes.getPasswords(); assertNotNull(passwords); assertNotNull(passwords.get("test2@example.com")); assertEquals("test2", passwords.get("test2@example.com").getPassword()); assertEquals("ID2", passwords.get("test2@example.com").getPasswordID()); assertNotNull(passwords.get("test5@example.com")); assertEquals("test5", passwords.get("test5@example.com").getPassword()); assertEquals("ID5", passwords.get("test5@example.com").getPasswordID()); }
From source file:org.cloudcoder.healthmonitor.HealthMonitor.java
private void sendEmail(Map<String, Info> infoMap, List<ReportItem> reportItems, boolean goodNews, boolean badNews, String reportEmailAddress) throws MessagingException, AddressException { Session session = createMailSession(config); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(reportEmailAddress)); message.addRecipient(RecipientType.TO, new InternetAddress(reportEmailAddress)); message.setSubject("CloudCoder health monitor report"); StringBuilder body = new StringBuilder(); body.append("<h1>CloudCoder health monitor report</h1>\n"); if (badNews) { body.append("<h2>Unhealthy instances</h2>\n"); body.append("<ul>\n"); for (ReportItem item : reportItems) { if (item.badNews()) { appendReportItem(body, item, infoMap); }/* w ww.ja v a 2 s . c o m*/ } body.append("</ul>\n"); } if (goodNews) { body.append("<h2>Healthy instances (back on line)</h2>\n"); body.append("<ul>\n"); for (ReportItem item : reportItems) { if (item.goodNews()) { appendReportItem(body, item, infoMap); } } body.append("</ul>\n"); } message.setContent(body.toString(), "text/html"); Transport.send(message); }
From source file:mitm.application.djigzo.james.mailets.RequestSenderCertificateTest.java
@Test public void testRequestCertificatePendingAvailable() throws Exception { MockMailetConfig mailetConfig = new MockMailetConfig(); String from = "from@example.com"; String to = "to@example.com"; proxy.addCertificateRequest(from);/*from w w w . jav a 2 s. c o m*/ RequestSenderCertificate mailet = new RequestSenderCertificate(); mailet.init(mailetConfig); MockMail mail = new MockMail(); MimeMessage message = new MimeMessage(MailSession.getDefaultSession()); message.setContent("test", "text/plain"); message.setFrom(new InternetAddress(from)); message.saveChanges(); mail.setMessage(message); Collection<MailAddress> recipients = new LinkedList<MailAddress>(); recipients.add(new MailAddress(to)); mail.setRecipients(recipients); mail.setSender(new MailAddress("somethingelse@example.com")); assertFalse(proxy.isUser(from)); assertFalse(proxy.isUser(to)); mailet.service(mail); assertEquals(INITIAL_KEY_STORE_SIZE, proxy.getKeyAndCertStoreSize()); assertFalse(proxy.isUser(to)); assertFalse(proxy.isUser(from)); }
From source file:org.openmhealth.reference.domain.User.java
/** * Verifies that an email address is a valid email address, but it does not * guarantee that the location that it references exists. * // w w w . j a v a 2s. c o m * @param email * The email address to be validated. * * @return The email address as an InternetAddress object. * * @throws OmhException * The email address is invalid. */ public static InternetAddress validateEmail(final String email) throws OmhException { if (email == null) { throw new OmhException("The email address is null"); } String trimmedEmail = email.trim(); if (trimmedEmail.length() == 0) { throw new OmhException("The email address is empty."); } // Create the InternetAddress object. InternetAddress result; try { result = new InternetAddress(email); } catch (AddressException e) { throw new OmhException("The email address is not a valid email address.", e); } // Validate the address. try { result.validate(); } catch (AddressException e) { throw new OmhException("The email address is not a valid email address.", e); } return result; }