List of usage examples for javax.mail.internet InternetAddress parse
public static InternetAddress[] parse(String addresslist, boolean strict) throws AddressException
From source file:org.mobicents.servlet.restcomm.email.EmailService.java
EmailResponse send(final Mail mail) { try {/* w w w . j a v a2 s . co m*/ InternetAddress from; if (mail.from() != null || !mail.from().equalsIgnoreCase("")) { from = new InternetAddress(mail.from()); } else { from = new InternetAddress(user); } final InternetAddress to = new InternetAddress(mail.to()); final MimeMessage email = new MimeMessage(session); email.setFrom(from); email.addRecipient(Message.RecipientType.TO, to); email.setSubject(mail.subject()); email.setText(mail.body()); email.addRecipients(Message.RecipientType.CC, InternetAddress.parse(mail.cc(), false)); email.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(mail.bcc(), false)); Transport.send(email); return new EmailResponse(mail); } catch (final MessagingException exception) { logger.error(exception.getMessage(), exception); return new EmailResponse(exception, exception.getMessage()); } }
From source file:org.pentaho.platform.repository.subscription.SubscriptionEmailContent.java
public boolean send() { String cc = null;//from w w w. java2 s. c om String bcc = null; String from = props.getProperty("mail.from.default"); String to = props.getProperty("to"); boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth")); String subject = props.getProperty("subject"); String body = props.getProperty("body"); logger.info("Going to send an email to " + to + " from " + from + "with the subject '" + subject + "' and the body " + body); try { // Get a Session object Session session; if (authenticate) { Authenticator authenticator = new EmailAuthenticator(); session = Session.getInstance(props, authenticator); } else { session = Session.getInstance(props); } // if debugging is not set in the email config file, then default to false if (!props.containsKey("mail.debug")) { //$NON-NLS-1$ session.setDebug(false); } // construct the message MimeMessage msg = new MimeMessage(session); Multipart multipart = new MimeMultipart(); if (from != null) { msg.setFrom(new InternetAddress(from)); } else { // There should be no way to get here logger.error("Email.ERROR_0012_FROM_NOT_DEFINED"); //$NON-NLS-1$ } if ((to != null) && (to.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); } if ((cc != null) && (cc.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); } if ((bcc != null) && (bcc.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); } if (subject != null) { msg.setSubject(subject, LocaleHelper.getSystemEncoding()); } if (body != null) { MimeBodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setContent(body, "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$ multipart.addBodyPart(textBodyPart); } // need to create a multi-part message... // create the Multipart and add its parts to it // create and fill the first message part IPentahoStreamSource source = attachment; if (source == null) { logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$ return false; } DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(source); // create the second message part MimeBodyPart attachmentBodyPart = new MimeBodyPart(); // attach the file to the message attachmentBodyPart.setDataHandler(new DataHandler(dataSource)); attachmentBodyPart.setFileName(attachmentName); multipart.addBodyPart(attachmentBodyPart); // add the Multipart to the message msg.setContent(multipart); msg.setHeader("X-Mailer", SubscriptionEmailContent.MAILER); //$NON-NLS-1$ msg.setSentDate(new Date()); Transport.send(msg); return true; // TODO: persist the content set for a while... } catch (SendFailedException e) { logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$ } catch (AuthenticationFailedException e) { logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$ } catch (Throwable e) { logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$ } return false; }
From source file:org.sigmah.server.mail.MailSenderImpl.java
@Override public void sendFile(Email email, String fileName, InputStream fileStream) throws EmailException { final String user = email.getAuthenticationUserName(); final String password = email.getAuthenticationPassword(); final Properties properties = new Properties(); properties.setProperty(MAIL_TRANSPORT_PROTOCOL, TRANSPORT_PROTOCOL); properties.setProperty(MAIL_SMTP_HOST, email.getHostName()); properties.setProperty(MAIL_SMTP_PORT, Integer.toString(email.getSmtpPort())); final StringBuilder toBuilder = new StringBuilder(); for (final String to : email.getToAddresses()) { if (toBuilder.length() > 0) { toBuilder.append(','); }// w w w . j a v a 2s. c o m toBuilder.append(to); } final StringBuilder ccBuilder = new StringBuilder(); if (email.getCcAddresses().length > 0) { for (final String cc : email.getCcAddresses()) { if (ccBuilder.length() > 0) { ccBuilder.append(','); } ccBuilder.append(cc); } } final Session session = javax.mail.Session.getInstance(properties); try { final DataSource attachment = new ByteArrayDataSource(fileStream, FileType.fromExtension(FileType.getExtension(fileName), FileType._DEFAULT).getContentType()); final Transport transport = session.getTransport(); if (password != null) { transport.connect(user, password); } else { transport.connect(); } final MimeMessage message = new MimeMessage(session); // Configures the headers. message.setFrom(new InternetAddress(email.getFromAddress(), false)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toBuilder.toString(), false)); if (email.getCcAddresses().length > 0) { message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccBuilder.toString(), false)); } message.setSubject(email.getSubject(), email.getEncoding()); // Html body part. final MimeMultipart textMultipart = new MimeMultipart("alternative"); final MimeBodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setContent(email.getContent(), "text/html; charset=\"" + email.getEncoding() + "\""); textMultipart.addBodyPart(htmlBodyPart); final MimeBodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setContent(textMultipart); // Attachment body part. final MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.setDataHandler(new DataHandler(attachment)); attachmentPart.setFileName(fileName); attachmentPart.setDescription(fileName); // Mail multipart content. final MimeMultipart contentMultipart = new MimeMultipart("related"); contentMultipart.addBodyPart(textBodyPart); contentMultipart.addBodyPart(attachmentPart); message.setContent(contentMultipart); message.saveChanges(); // Sends the mail. transport.sendMessage(message, message.getAllRecipients()); } catch (UnsupportedEncodingException ex) { throw new EmailException( "An error occured while encoding the mail content to '" + email.getEncoding() + "'.", ex); } catch (IOException ex) { throw new EmailException("An error occured while reading the attachment of an email.", ex); } catch (MessagingException ex) { throw new EmailException("An error occured while sending an email.", ex); } }
From source file:sendhtml.java
public sendhtml(String[] argv) { String to, subject = null, from = null, cc = null, bcc = null, url = null; String mailhost = null;/*from w w w . j a v a 2 s .c o m*/ String mailer = "sendhtml"; String protocol = null, host = null, user = null, password = null; String record = null; // name of folder in which to record mail boolean debug = false; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int optind; for (optind = 0; optind < argv.length; optind++) { if (argv[optind].equals("-T")) { protocol = argv[++optind]; } else if (argv[optind].equals("-H")) { host = argv[++optind]; } else if (argv[optind].equals("-U")) { user = argv[++optind]; } else if (argv[optind].equals("-P")) { password = argv[++optind]; } else if (argv[optind].equals("-M")) { mailhost = argv[++optind]; } else if (argv[optind].equals("-f")) { record = argv[++optind]; } else if (argv[optind].equals("-s")) { subject = argv[++optind]; } else if (argv[optind].equals("-o")) { // originator from = argv[++optind]; } else if (argv[optind].equals("-c")) { cc = argv[++optind]; } else if (argv[optind].equals("-b")) { bcc = argv[++optind]; } else if (argv[optind].equals("-L")) { url = argv[++optind]; } else if (argv[optind].equals("-d")) { debug = true; } else if (argv[optind].equals("--")) { optind++; break; } else if (argv[optind].startsWith("-")) { System.out.println("Usage: sendhtml [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]"); System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]"); System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [address]"); System.exit(1); } else { break; } } try { if (optind < argv.length) { // XXX - concatenate all remaining arguments to = argv[optind]; System.out.println("To: " + to); } else { System.out.print("To: "); System.out.flush(); to = in.readLine(); } if (subject == null) { System.out.print("Subject: "); System.out.flush(); subject = in.readLine(); } else { System.out.println("Subject: " + subject); } Properties props = System.getProperties(); // XXX - could use Session.getTransport() and Transport.connect() // XXX - assume we're using SMTP if (mailhost != null) props.put("mail.smtp.host", mailhost); // Get a Session object Session session = Session.getInstance(props, null); if (debug) session.setDebug(true); // construct the message Message msg = new MimeMessage(session); if (from != null) msg.setFrom(new InternetAddress(from)); else msg.setFrom(); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); if (cc != null) msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); if (bcc != null) msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); msg.setSubject(subject); collect(in, msg); msg.setHeader("X-Mailer", mailer); msg.setSentDate(new Date()); // send the thing off Transport.send(msg); System.out.println("\nMail was sent successfully."); // Keep a copy, if requested. if (record != null) { // Get a Store object Store store = null; if (url != null) { URLName urln = new URLName(url); store = session.getStore(urln); store.connect(); } else { if (protocol != null) store = session.getStore(protocol); else store = session.getStore(); // Connect if (host != null || user != null || password != null) store.connect(host, user, password); else store.connect(); } // Get record Folder. Create if it does not exist. Folder folder = store.getFolder(record); if (folder == null) { System.err.println("Can't get record folder."); System.exit(1); } if (!folder.exists()) folder.create(Folder.HOLDS_MESSAGES); Message[] msgs = new Message[1]; msgs[0] = msg; folder.appendMessages(msgs); System.out.println("Mail was recorded successfully."); } } catch (Exception e) { e.printStackTrace(); } }
From source file:sendhtml.java
public sendhtml(String[] argv) { String to, subject = null, from = null, cc = null, bcc = null, url = null; String mailhost = null;//from w w w. ja v a 2 s . co m String mailer = "sendhtml"; String protocol = null, host = null, user = null, password = null; String record = null; // name of folder in which to record mail boolean debug = false; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int optind; for (optind = 0; optind < argv.length; optind++) { if (argv[optind].equals("-T")) { protocol = argv[++optind]; } else if (argv[optind].equals("-H")) { host = argv[++optind]; } else if (argv[optind].equals("-U")) { user = argv[++optind]; } else if (argv[optind].equals("-P")) { password = argv[++optind]; } else if (argv[optind].equals("-M")) { mailhost = argv[++optind]; } else if (argv[optind].equals("-f")) { record = argv[++optind]; } else if (argv[optind].equals("-s")) { subject = argv[++optind]; } else if (argv[optind].equals("-o")) { // originator from = argv[++optind]; } else if (argv[optind].equals("-c")) { cc = argv[++optind]; } else if (argv[optind].equals("-b")) { bcc = argv[++optind]; } else if (argv[optind].equals("-L")) { url = argv[++optind]; } else if (argv[optind].equals("-d")) { debug = true; } else if (argv[optind].equals("--")) { optind++; break; } else if (argv[optind].startsWith("-")) { System.out.println("Usage: sendhtml [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]"); System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]"); System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [address]"); System.exit(1); } else { break; } } try { if (optind < argv.length) { // XXX - concatenate all remaining arguments to = argv[optind]; System.out.println("To: " + to); } else { System.out.print("To: "); System.out.flush(); to = in.readLine(); } if (subject == null) { System.out.print("Subject: "); System.out.flush(); subject = in.readLine(); } else { System.out.println("Subject: " + subject); } Properties props = System.getProperties(); // XXX - could use Session.getTransport() and Transport.connect() // XXX - assume we're using SMTP if (mailhost != null) props.put("mail.smtp.host", mailhost); // Get a Session object Session session = Session.getInstance(props, null); if (debug) session.setDebug(true); // construct the message Message msg = new MimeMessage(session); if (from != null) msg.setFrom(new InternetAddress(from)); else msg.setFrom(); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); if (cc != null) msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); if (bcc != null) msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); msg.setSubject(subject); collect(in, msg); msg.setHeader("X-Mailer", mailer); msg.setSentDate(new Date()); // send the thing off Transport.send(msg); System.out.println("\nMail was sent successfully."); // Keep a copy, if requested. if (record != null) { // Get a Store object Store store = null; if (url != null) { URLName urln = new URLName(url); store = session.getStore(urln); store.connect(); } else { if (protocol != null) store = session.getStore(protocol); else store = session.getStore(); // Connect if (host != null || user != null || password != null) store.connect(host, user, password); else store.connect(); } // Get record Folder. Create if it does not exist. Folder folder = store.getFolder(record); if (folder == null) { System.err.println("Can't get record folder."); System.exit(1); } if (!folder.exists()) folder.create(Folder.HOLDS_MESSAGES); Message[] msgs = new Message[1]; msgs[0] = msg; folder.appendMessages(msgs); System.out.println("Mail was recorded successfully."); } } catch (Exception e) { e.printStackTrace(); } }
From source file:org.exoplatform.forum.ForumUtils.java
public static boolean isValidEmailAddresses(String addressList) { if (isEmpty(addressList)) return true; addressList = StringUtils.remove(addressList, " "); addressList = StringUtils.replace(addressList, ";", COMMA); try {/*from w w w . jav a 2s . co m*/ InternetAddress[] iAdds = InternetAddress.parse(addressList, true); String emailRegex = "[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[_A-Za-z0-9-.]+\\.[A-Za-z]{2,5}"; for (int i = 0; i < iAdds.length; i++) { if (!iAdds[i].getAddress().matches(emailRegex)) return false; } } catch (AddressException e) { return false; } return true; }
From source file:org.exoplatform.platform.portlet.juzu.notificationsAdmin.NotificationsAdministration.java
public static boolean isValidEmailAddresses(String addressList) { if (addressList == null || addressList.trim().length() == 0) return false; addressList = StringUtils.remove(addressList, " "); addressList = StringUtils.replace(addressList, ";", ","); try {/* w ww . j a v a 2 s. c om*/ InternetAddress[] iAdds = InternetAddress.parse(addressList, true); String emailRegex = "[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[_A-Za-z0-9-.]+\\.[A-Za-z]{2,5}"; for (int i = 0; i < iAdds.length; i++) { if (!iAdds[i].getAddress().matches(emailRegex)) return false; } } catch (AddressException e) { return false; } return true; }
From source file:org.restcomm.connect.email.EmailService.java
EmailResponse sendEmailSsL(final Mail mail) { try {// ww w . j av a2 s . c om InternetAddress from; if (mail.from() != null || !mail.from().equalsIgnoreCase("")) { from = new InternetAddress(mail.from()); } else { from = new InternetAddress(user); } final InternetAddress to = new InternetAddress(mail.to()); final MimeMessage email = new MimeMessage(session); email.setFrom(from); email.addRecipient(Message.RecipientType.TO, to); email.setSubject(mail.subject()); email.setText(mail.body()); email.addRecipients(Message.RecipientType.CC, InternetAddress.parse(mail.cc(), false)); email.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(mail.bcc(), false)); //Transport.send(email); transport.connect(host, Integer.parseInt(port), user, password); transport.sendMessage(email, email.getRecipients(Message.RecipientType.TO)); return new EmailResponse(mail); } catch (final MessagingException exception) { logger.error(exception.getMessage(), exception); return new EmailResponse(exception, exception.getMessage()); } }
From source file:org.exoplatform.commons.notification.NotificationUtils.java
public static boolean isValidEmailAddresses(String addressList) { if (addressList == null || addressList.length() < 0) return false; addressList = StringUtils.replace(addressList, ";", ","); try {// ww w.j ava2 s . c o m InternetAddress[] iAdds = InternetAddress.parse(addressList, true); for (int i = 0; i < iAdds.length; i++) { Matcher matcher = EMAIL_PATTERN.matcher(iAdds[i].getAddress().trim()); if (!matcher.find()) return false; } } catch (AddressException e) { return false; } return true; }
From source file:com.vaushell.superpipes.dispatch.ErrorMailer.java
private void sendHTML(final String message) throws MessagingException, IOException { if (message == null || message.isEmpty()) { throw new IllegalArgumentException("message"); }/*from w w w. j a v a 2 s. c o m*/ final String host = properties.getConfigString("host"); final Properties props = System.getProperties(); props.setProperty("mail.smtp.host", host); final String port = properties.getConfigString("port", null); if (port != null) { props.setProperty("mail.smtp.port", port); } if ("true".equalsIgnoreCase(properties.getConfigString("ssl", null))) { props.setProperty("mail.smtp.ssl.enable", "true"); } final Session session = Session.getInstance(props, null); // session.setDebug( true ); final javax.mail.Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(properties.getConfigString("from"))); msg.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(properties.getConfigString("to"), false)); msg.setSubject("superpipes error message"); msg.setDataHandler(new DataHandler(new ByteArrayDataSource(message, "text/html"))); msg.setHeader("X-Mailer", "superpipes"); Transport t = null; try { t = session.getTransport("smtp"); final String username = properties.getConfigString("username", null); final String password = properties.getConfigString("password", null); if (username == null || password == null) { t.connect(); } else { if (port == null || port.isEmpty()) { t.connect(host, username, password); } else { t.connect(host, Integer.parseInt(port), username, password); } } t.sendMessage(msg, msg.getAllRecipients()); } finally { if (t != null) { t.close(); } } }