List of usage examples for javax.mail.internet AddressException getMessage
public String getMessage()
From source file:org.vosao.utils.EmailUtil.java
/** * Send email with html content and attachments. * @param htmlBody//from w ww. ja va2 s. c om * @param subject * @param fromAddress * @param fromText * @param toAddress * @return null if OK or error message. */ public static String sendEmail(final String htmlBody, final String subject, final String fromAddress, final String fromText, final String toAddress, final List<FileItem> files) { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); try { Multipart mp = new MimeMultipart(); MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(htmlBody, "text/html"); htmlPart.setHeader("Content-type", "text/html; charset=UTF-8"); mp.addBodyPart(htmlPart); for (FileItem item : files) { MimeBodyPart attachment = new MimeBodyPart(); attachment.setFileName(item.getFilename()); String mimeType = MimeType.getContentTypeByExt(FolderUtil.getFileExt(item.getFilename())); DataSource ds = new ByteArrayDataSource(item.getData(), mimeType); attachment.setDataHandler(new DataHandler(ds)); mp.addBodyPart(attachment); } MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(fromAddress, fromText)); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress, toAddress)); msg.setSubject(subject, "UTF-8"); msg.setContent(mp); Transport.send(msg); return null; } catch (AddressException e) { return e.getMessage(); } catch (MessagingException e) { return e.getMessage(); } catch (UnsupportedEncodingException e) { return e.getMessage(); } }
From source file:org.vosao.utils.EmailUtil.java
/** * Send email with html content and attachments. * @param htmlBody/*w w w .j av a2 s . c om*/ * @param subject * @param fromAddress * @param fromText * @param toAddress * @return null if OK or error message. */ public static String sendEmail(final String htmlBody, final String subject, final String fromAddress, final String fromText, final String toAddress, final List<FileItem> files) { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); try { Multipart mp = new MimeMultipart(); MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(htmlBody, "text/html"); htmlPart.setHeader("Content-type", "text/html; charset=UTF-8"); mp.addBodyPart(htmlPart); for (FileItem item : files) { MimeBodyPart attachment = new MimeBodyPart(); attachment.setFileName(item.getFilename()); String mimeType = MimeType.getContentTypeByExt(FolderUtil.getFileExt(item.getFilename())); if (mimeType.equals("text/plain")) { mimeType = MimeType.DEFAULT; } DataSource ds = new ByteArrayDataSource(item.getData(), mimeType); attachment.setDataHandler(new DataHandler(ds)); mp.addBodyPart(attachment); } MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(fromAddress, fromText)); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress, toAddress)); msg.setSubject(subject, "UTF-8"); msg.setContent(mp); Transport.send(msg); return null; } catch (AddressException e) { return e.getMessage(); } catch (MessagingException e) { return e.getMessage(); } catch (UnsupportedEncodingException e) { return e.getMessage(); } }
From source file:org.jenkinsci.plugins.send_mail_builder.SendMailBuilder.java
private static final InternetAddress[] toInternetAddresses(final BuildListener listener, final String addresses, final String charset) throws UnsupportedEncodingException { final String defaultSuffix = Mailer.descriptor().getDefaultSuffix(); final Set<InternetAddress> rcp = new LinkedHashSet<InternetAddress>(); final StringTokenizer tokens = new StringTokenizer(addresses); while (tokens.hasMoreTokens()) { String address = tokens.nextToken(); // if not a valid address (i.e. no '@'), then try adding suffix if (!address.contains("@") && defaultSuffix != null && defaultSuffix.contains("@")) { address += defaultSuffix;// w w w . j a v a2 s.co m } try { rcp.add(Mailer.StringToAddress(address, charset)); } catch (final AddressException e) { // report bad address, but try to send to other addresses listener.getLogger().println("Unable to send to address: " + address); e.printStackTrace(listener.error(e.getMessage())); } } return rcp.toArray(new InternetAddress[0]); }
From source file:com.flexive.shared.FxMailUtils.java
/** * Sends an email//ww w .j av a 2 s . c o m * * @param SMTPServer IP Address of the SMTP server * @param subject subject of the email * @param textBody plain text * @param htmlBody html text * @param to recipient * @param cc cc recepient * @param bcc bcc recipient * @param from sender * @param replyTo reply-to address * @param mimeAttachments strings containing mime encoded attachments * @throws FxApplicationException on errors */ public static void sendMail(String SMTPServer, String subject, String textBody, String htmlBody, String to, String cc, String bcc, String from, String replyTo, String... mimeAttachments) throws FxApplicationException { try { // Set the mail server java.util.Properties properties = System.getProperties(); if (SMTPServer != null) properties.put("mail.smtp.host", SMTPServer); // Get a session and create a new message javax.mail.Session session = javax.mail.Session.getInstance(properties, null); MimeMessage msg = new MimeMessage(session); // Set the sender if (StringUtils.isBlank(from)) msg.setFrom(); // Uses local IP Adress and the user under which the server is running else { msg.setFrom(createAddress(from)); } if (!StringUtils.isBlank(replyTo)) msg.setReplyTo(encodePersonal(InternetAddress.parse(replyTo, false))); // Set the To, Cc and Bcc fields if (!StringUtils.isBlank(to)) msg.setRecipients(MimeMessage.RecipientType.TO, encodePersonal(InternetAddress.parse(to, false))); if (!StringUtils.isBlank(cc)) msg.setRecipients(MimeMessage.RecipientType.CC, encodePersonal(InternetAddress.parse(cc, false))); if (!StringUtils.isBlank(bcc)) msg.setRecipients(MimeMessage.RecipientType.BCC, encodePersonal(InternetAddress.parse(bcc, false))); // Set the subject msg.setSubject(subject, "UTF-8"); String sMainType = "Multipart/Alternative;\n\tboundary=\"" + BOUNDARY1 + "\""; StringBuilder body = new StringBuilder(5000); if (mimeAttachments.length > 0) { sMainType = "Multipart/Mixed;\n\tboundary=\"" + BOUNDARY2 + "\""; body.append("This is a multi-part message in MIME format.\n\n"); body.append("--" + BOUNDARY2 + "\n"); body.append("Content-Type: Multipart/Alternative;\n\tboundary=\"" + BOUNDARY1 + "\"\n\n\n"); } if (textBody.length() > 0) { body.append("--" + BOUNDARY1 + "\n"); body.append("Content-Type: text/plain; charset=\"UTF-8\"\n"); body.append("Content-Transfer-Encoding: quoted-printable\n\n"); body.append(encodeQuotedPrintable(textBody)).append("\n"); } if (htmlBody.length() > 0) { body.append("--" + BOUNDARY1 + "\n"); body.append("Content-Type: text/html;\n\tcharset=\"UTF-8\"\n"); body.append("Content-Transfer-Encoding: quoted-printable\n\n"); if (htmlBody.toLowerCase().indexOf("<html>") < 0) { body.append("<HTML><HEAD>\n<TITLE></TITLE>\n"); body.append( "<META http-equiv=3DContent-Type content=3D\"text/html; charset=3Dutf-8\"></HEAD>\n<BODY>\n"); body.append(encodeQuotedPrintable(htmlBody)).append("</BODY></HTML>\n"); } else body.append(encodeQuotedPrintable(htmlBody)).append("\n"); } body.append("\n--" + BOUNDARY1 + "--\n"); if (mimeAttachments.length > 0) { for (String mimeAttachment : mimeAttachments) { body.append("\n--" + BOUNDARY2 + "\n"); body.append(mimeAttachment).append("\n"); } body.append("\n--" + BOUNDARY2 + "--\n"); } msg.setDataHandler( new javax.activation.DataHandler(new ByteArrayDataSource(body.toString(), sMainType))); // Set the header msg.setHeader("X-Mailer", "JavaMailer"); // Set the sent date msg.setSentDate(new java.util.Date()); // Send the message javax.mail.Transport.send(msg); } catch (AddressException e) { throw new FxApplicationException(e, "ex.messaging.mail.address", e.getRef()); } catch (javax.mail.MessagingException e) { throw new FxApplicationException(e, "ex.messaging.mail.send", e.getMessage()); } catch (IOException e) { throw new FxApplicationException(e, "ex.messaging.mail.send", e.getMessage()); } catch (EncoderException e) { throw new FxApplicationException(e, "ex.messaging.mail.send", e.getMessage()); } }
From source file:ru.org.linux.user.EditRegisterRequestValidator.java
@Override public void validate(Object o, Errors errors) { EditRegisterRequest form = (EditRegisterRequest) o; if (!Strings.isNullOrEmpty(form.getTown())) { if (StringUtil.escapeHtml(form.getTown()).length() > TOWN_LENGTH) { errors.rejectValue("town", null, " (? " + TOWN_LENGTH + " ?)"); }// w w w. j a v a 2 s.co m } if (!Strings.isNullOrEmpty(form.getUrl()) && !URLUtil.isUrl(form.getUrl())) { errors.rejectValue("url", null, "? URL"); } if (form.getPassword2() != null && form.getPassword() != null && !form.getPassword().equals(form.getPassword2())) { errors.reject(null, " ?"); } if (!Strings.isNullOrEmpty(form.getPassword()) && form.getPassword().length() < MIN_PASSWORD_LEN) { errors.reject(null, "? , ? : " + MIN_PASSWORD_LEN); } if (Strings.isNullOrEmpty(form.getEmail())) { errors.rejectValue("email", null, "? e-mail"); } else { try { InternetAddress mail = new InternetAddress(form.getEmail()); checkEmail(mail, errors); } catch (AddressException e) { errors.rejectValue("email", null, "? e-mail: " + e.getMessage()); } } }
From source file:org.apache.oodt.cas.crawl.action.EmailNotification.java
@Override public boolean performAction(File product, Metadata metadata) throws CrawlerActionException { try {/*from w w w. j av a2 s . co 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; } }
From source file:ru.org.linux.user.RegisterRequestValidator.java
@Override public void validate(Object o, Errors errors) { RegisterRequest form = (RegisterRequest) o; /*//w ww .j a v a 2 s.co m Nick validate */ String nick = form.getNick(); if (Strings.isNullOrEmpty(nick)) { errors.rejectValue("nick", null, " nick"); } if (nick != null && !StringUtil.checkLoginName(nick)) { errors.rejectValue("nick", null, " ? ?"); } if (nick != null && nick.length() > User.MAX_NICK_LENGTH) { errors.rejectValue("nick", null, "? ? ?"); } /* Password validate */ String password = Strings.emptyToNull(form.getPassword()); String password2 = Strings.emptyToNull(form.getPassword2()); if (Strings.isNullOrEmpty(password)) { errors.reject("password", null, " ?"); } if (Strings.isNullOrEmpty(password2)) { errors.reject("password2", null, " ?"); } if (password != null && password.equalsIgnoreCase(nick)) { errors.reject(password, null, " ? ? "); } if (form.getPassword2() != null && form.getPassword() != null && !form.getPassword().equals(form.getPassword2())) { errors.reject(null, " ?"); } if (!Strings.isNullOrEmpty(form.getPassword()) && form.getPassword().length() < MIN_PASSWORD_LEN) { errors.reject("password", null, "? , ? : " + MIN_PASSWORD_LEN); } /* Email validate */ if (Strings.isNullOrEmpty(form.getEmail())) { errors.rejectValue("email", null, "? e-mail"); } else { try { InternetAddress mail = new InternetAddress(form.getEmail()); checkEmail(mail, errors); } catch (AddressException e) { errors.rejectValue("email", null, "? e-mail: " + e.getMessage()); } } /* Rules validate */ if (Strings.isNullOrEmpty(form.getRules()) || !"okay".equals(form.getRules())) { errors.reject("rules", null, " ??? ? "); } }
From source file:org.hyperic.hq.ui.action.resource.common.monitor.alerts.config.AddOthersForm.java
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { if (!shouldValidate(mapping, request)) return null; log.debug("validating email addresses: " + emailAddresses); ActionErrors errs = super.validate(mapping, request); if (null == errs && (emailAddresses == null || emailAddresses.length() == 0)) { // A special case, BaseValidatorForm will return null if Ok is // clicked and input is null, indicating a PrepareForm // action is occurring. This is tricky. However, it also // returns null if no validations failed. This is really // lame, in my opinion. return null; } else {//from w ww . j a v a 2 s . c o m errs = new ActionErrors(); } try { InternetAddress[] addresses = InternetAddress.parse(emailAddresses); } catch (AddressException e) { if (e.getRef() == null) { ActionMessage err = new ActionMessage("alert.config.error.InvalidEmailAddresses", e.getMessage()); errs.add("emailAddresses", err); } else { ActionMessage err = new ActionMessage("alert.config.error.InvalidEmailAddress", e.getRef(), e.getMessage()); errs.add("emailAddresses", err); } } return errs; }
From source file:fr.gael.dhus.messaging.mail.MailServer.java
public void send(Email email, String to, String cc, String bcc, String subject) throws EmailException { email.setHostName(getSmtpServer());// ww w . ja v a 2 s . co m email.setSmtpPort(getPort()); if (getUsername() != null) { email.setAuthentication(getUsername(), getPassword()); } if (getFromMail() != null) { if (getFromName() != null) email.setFrom(getFromMail(), getFromName()); else email.setFrom(getFromMail()); } if (getReplyto() != null) { try { email.setReplyTo(ImmutableList.of(new InternetAddress(getReplyto()))); } catch (AddressException e) { logger.error("Cannot configure Reply-to (" + getReplyto() + ") into the mail: " + e.getMessage()); } } // Message configuration email.setSubject("[" + cfgManager.getNameConfiguration().getShortName() + "] " + subject); email.addTo(to); // Add CCed if (cc != null) { email.addCc(cc); } // Add BCCed if (bcc != null) { email.addBcc(bcc); } email.setStartTLSEnabled(isTls()); try { email.send(); } catch (EmailException e) { logger.error("Cannot send email: " + e.getMessage()); throw e; } }
From source file:org.openhab.binding.mail.action.SendMailActions.java
@RuleAction(label = "Send Text Mail", description = "sends a text mail with several URL attachments") public @ActionOutput(name = "success", type = "java.lang.Boolean") Boolean sendMail( @ActionInput(name = "recipient") @Nullable String recipient, @ActionInput(name = "subject") @Nullable String subject, @ActionInput(name = "text") @Nullable String text, @ActionInput(name = "urlList") @Nullable List<String> urlStringList) { if (recipient == null) { logger.info("can't send to missing recipient"); return false; }/*from www. ja v a2s. c o m*/ try { MailBuilder builder = new MailBuilder(recipient); if (subject != null && !subject.isEmpty()) { builder.withSubject(subject); } if (text != null && !text.isEmpty()) { builder.withText(text); } if (urlStringList != null) { for (String urlString : urlStringList) { builder.withURLAttachment(urlString); } } if (handler == null) { logger.info("handler is null, can't send mail"); return false; } else { return handler.sendMail(builder.build()); } } catch (AddressException e) { logger.info("could not send mail: {}", e.getMessage()); return false; } catch (MalformedURLException e) { logger.info("could not send mail: {}", e.getMessage()); return false; } catch (EmailException e) { logger.info("could not send mail: {}", e.getMessage()); return false; } }