List of usage examples for javax.mail.internet InternetAddress InternetAddress
public InternetAddress(String address) throws AddressException
From source file:com.tdclighthouse.commons.mail.util.MailClient.java
public void sendMail(String from, String[] to, Mail mail) throws MessagingException, AddressException { // a brief validation if ((from == null) || "".equals(from) || (to.length == 0) || (mail == null)) { throw new IllegalArgumentException(); }/* ww w . ja v a2 s .c om*/ Session session = getSession(); // Define a new mail message MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); for (int i = 0; i < to.length; i++) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(to[i])); } message.setSubject(mail.getSubject(), "utf-8"); // use a MimeMultipart as we need to handle the file attachments Multipart multipart = new MimeMultipart("alternative"); if ((mail.getMessageBody() != null) && !"".equals(mail.getMessageBody())) { // add the message body to the mime message BodyPart textPart = new MimeBodyPart(); textPart.setContent(mail.getMessageBody(), "text/plain; charset=utf-8"); // sets type to "text/plain" multipart.addBodyPart(textPart); } if (mail.getHtmlBody() != null) { BodyPart pixPart = new MimeBodyPart(); pixPart.setContent(mail.getHtmlBody(), "text/html; charset=utf-8"); multipart.addBodyPart(pixPart); } // add any file attachments to the message addAtachments(mail.getAttachments(), multipart); // Put all message parts in the message message.setContent(multipart); // Send the message Transport.send(message); }
From source file:edu.gmu.csd.validation.Validation.java
public void validateEmailAddress(FacesContext context, UIComponent componentToValidate, Object value) throws ValidationException { boolean isEmailValid = false; String emailAddress = (String) value; if (emailAddress == null) { isEmailValid = false;//from w w w .j a v a 2 s.c om } try { InternetAddress emailAddr = new InternetAddress(emailAddress); emailAddr.validate(); isEmailValid = true; } catch (AddressException ex) { isEmailValid = false; } if (!isEmailValid) { FacesMessage message = new FacesMessage("Your email address should be of valid format."); throw new ValidatorException(message); } }
From source file:jease.cms.service.Mails.java
/** * Sends an email synchronously.// w w w.j a va 2s. c o m */ public void send(String sender, String recipients, String subject, String text) throws MessagingException { if (properties != null) { Session session = Session.getInstance(properties.asProperties(), new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(properties.getUser(), properties.getPassword()); } }); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(sender)); message.setReplyTo(new InternetAddress[] { new InternetAddress(sender) }); message.setRecipients(Message.RecipientType.TO, recipients); message.setSubject(subject, "utf-8"); message.setSentDate(new Date()); message.setHeader("Content-Type", "text/plain; charset=\"utf-8\""); message.setHeader("Content-Transfer-Encoding", "quoted-printable"); message.setText(text, "utf-8"); Transport.send(message); } }
From source file:com.seer.datacruncher.utils.mail.MailService.java
public void sendMail(MailConfig mailConfig) throws Exception { String logMsg = "MailService:sendMail():"; InputStream attachment = null; MimeMessage mimeMessage = null;//from w ww . j av a 2s .com MimeMessageHelper helper = null; try { mimeMessage = mailSender.createMimeMessage(); helper = new MimeMessageHelper(mimeMessage, true); helper.setText(mailConfig.getText(), true); if (StringUtils.isEmpty(mailConfig.getMailTo())) { log.error("Invalid or empty 'toAddress' configured!!"); throw new Exception("Invalid or empty 'toAddress' configured"); } if (StringUtils.isEmpty(mailConfig.getMailFrom())) { log.error("Invalid or empty 'FromAddress' configured!!"); throw new Exception("Invalid or empty 'FromAddress' configured"); } if (!isEmailValid(mailConfig.getMailFrom())) { log.error("Invalid 'FromAddress' configured!!"); throw new Exception("Invalid 'FromAddress' configured"); } helper.setFrom(new InternetAddress(mailConfig.getMailFrom())); helper.setSubject(mailConfig.getSubject()); helper.setTo(getToAddress(mailConfig.getMailTo())); attachment = mailConfig.getAttachment(); if (attachment != null) { StreamAttachmentDataSource datasource = new StreamAttachmentDataSource(mailConfig.getAttachment()); helper.addAttachment(mailConfig.getAttachmentName(), datasource); } this.mailSender.send(mimeMessage); } catch (AuthenticationFailedException afex) { log.error(logMsg + "AuthenticationFailedException:", afex); throw new Exception("AuthenticationFailedException", afex); } catch (MessagingException mex) { log.error(logMsg + "Exception:", mex); throw new Exception("MessagingException", mex); } catch (Exception ex) { log.error(logMsg + "Exception:", ex); throw ex; } }
From source file:business.controllers.LabController.java
public void transferLabData(Lab body, Lab lab) { lab.setName(body.getName());/*from w ww. j a va 2 s . c om*/ lab.setHubAssistanceEnabled(body.isHubAssistanceEnabled()); if (lab.getContactData() == null) { lab.setContactData(new ContactData()); } lab.getContactData().copy(body.getContactData()); Set<String> emailAddresses = new LinkedHashSet<>(); for (String email : body.getEmailAddresses()) { try { InternetAddress address = new InternetAddress(email); address.validate(); emailAddresses.add(email.trim().toLowerCase()); } catch (AddressException e) { throw new EmailAddressInvalid(email); } } lab.setEmailAddresses(new ArrayList<>(emailAddresses)); }
From source file:common.email.MailServiceImpl.java
/** * this method sends email using a given template * @param subject subject of a mail//from w w w . j ava 2 s . c o m * @param recipientEmail email receiver adress * @param mail mail text to send * @param from will be set * @return true if send succeed * @throws java.io.FileNotFoundException * @throws java.io.IOException */ protected boolean postMail(String subject, String recipientEmail, String from, String mail) throws IOException { try { Properties props = new Properties(); //props.put("mailHost", mailHost); Session session = Session.getInstance(props); // construct the message javax.mail.Message msg = new javax.mail.internet.MimeMessage(session); if (from == null) { msg.setFrom(); } else { try { msg.setFrom(new InternetAddress(from)); } catch (MessagingException ex) { logger.error(ex); } } msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false)); msg.setSubject(subject); msg.setSentDate(new Date()); //msg.setHeader("", user) msg.setDataHandler(new DataHandler(new ByteArrayDataSource(mail, "text/html; charset=UTF-8"))); SMTPTransport t = (SMTPTransport) session.getTransport("smtp"); t.connect(mailHost, user, password); Address[] a = msg.getAllRecipients(); t.sendMessage(msg, a); t.close(); return true; } catch (MessagingException ex) { logger.error(ex); ex.printStackTrace(); return false; } }
From source file:fr.xebia.cocktail.MailService.java
@Inject public MailService(@Named("smtpProperties") Properties smtpProperties) throws MessagingException { if (Strings.isNullOrEmpty(smtpProperties.getProperty("mail.username"))) { logger.info("Initialize anonymous mail session"); mailSession = Session.getInstance(smtpProperties); } else {/*ww w .jav a 2 s . c o m*/ final String username = smtpProperties.getProperty("mail.username"); final String password = smtpProperties.getProperty("mail.password"); logger.info("Initialize mail session with username='{}', password='xxx'", username); mailSession = Session.getInstance(smtpProperties, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); } fromAddress = new InternetAddress(smtpProperties.getProperty("mail.from")); }
From source file:com.keybox.manage.action.UserPasswordResetAction.java
/** * PW Reset Submit// w w w .ja v a2 s . c o m * @return <strong>PW Reset Page</strong>, if PW Reset enabled <br> * <strong>Error Page</strong>, if PW Reset disabled or Email empty */ @Action(value = "/pwResetSubmit", results = { @Result(name = "input", location = "/pw_reset.jsp"), @Result(name = "error", location = "/error.jsp") }) public String pwResetSubmit() { if (pwMailResetEnabled && StringUtils.isNotEmpty(email)) { try { //EMail Address validate Test InternetAddress internetAddress = new InternetAddress(email); internetAddress.validate(); //Reset Password and send mail if (UserDB.resetPWMail(email)) { addActionMessage(PW_RESET_MASSAGE); addActionError(null); } else { addActionMessage(null); addActionError(ERROR_MASSAGE); } } catch (AddressException e) { addActionMessage(null); addActionError(INVALID_MAIL_MASSAGE); } return INPUT; } else { return ERROR; } }
From source file:com.redhat.rhn.common.messaging.SmtpMail.java
/** * Create a mailer./*from w w w . java 2s.c o m*/ */ public SmtpMail() { log.debug("Constructed new SmtpMail."); disallowedDomains = Config.get().getStringArray("web.disallowed_mail_domains"); restrictedDomains = Config.get().getStringArray("web.restrict_mail_domains"); Config c = Config.get(); smtpHost = c.getString(ConfigDefaults.WEB_SMTP_SERVER, "localhost"); String from = c.getString(ConfigDefaults.WEB_DEFAULT_MAIL_FROM); // Get system properties Properties props = System.getProperties(); // Setup mail server props.put("mail.smtp.host", smtpHost); // Get session Session session = Session.getDefaultInstance(props, null); try { message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); } catch (AddressException me) { String msg = "Malformed address in traceback configuration: " + from; log.warn(msg); throw new JavaMailException(msg, me); } catch (MessagingException me) { String msg = "MessagingException while trying to send email: " + me.toString(); log.warn(msg); throw new JavaMailException(msg, me); } }
From source file:gov.nih.nci.protexpress.ui.actions.registration.EmailUtil.java
private static MimeMessage constructMessage(List<String> mailRecipients, String from, String mailSubject) throws MessagingException { Validate.notEmpty(mailRecipients, "No email recipients are specified"); if (StringUtils.isEmpty(mailSubject)) { LOG.info("No email subject specified"); }//ww w . java2 s. c o m List<Address> addresses = new ArrayList<Address>(); for (String recipient : mailRecipients) { addresses.add(new InternetAddress(recipient)); } MimeMessage message = new MimeMessage(mailSession); message.setRecipients(Message.RecipientType.TO, addresses.toArray(new Address[addresses.size()])); message.setFrom(new InternetAddress(from)); message.setSubject(mailSubject); return message; }