Java Code Examples for javax.mail.internet.InternetAddress#parse()

The following examples show how to use javax.mail.internet.InternetAddress#parse() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MimeMessageHelper.java    From java-technology-stack with MIT License 5 votes vote down vote up
private InternetAddress parseAddress(String address) throws MessagingException {
	InternetAddress[] parsed = InternetAddress.parse(address);
	if (parsed.length != 1) {
		throw new AddressException("Illegal address", address);
	}
	InternetAddress raw = parsed[0];
	try {
		return (getEncoding() != null ?
				new InternetAddress(raw.getAddress(), raw.getPersonal(), getEncoding()) : raw);
	}
	catch (UnsupportedEncodingException ex) {
		throw new MessagingException("Failed to parse embedded personal name to correct encoding", ex);
	}
}
 
Example 2
Source File: Forward.java    From james-project with Apache License 2.0 5 votes vote down vote up
private InternetAddress[] extractAddresses(String addressList) throws MessagingException {
    try {
        return InternetAddress.parse(addressList, false);
    } catch (AddressException e) {
        throw new MessagingException("Exception thrown in getRecipients() parsing: " + addressList, e);
    }
}
 
Example 3
Source File: Emailer.java    From olat with Apache License 2.0 5 votes vote down vote up
private boolean sendEmail(String from, String mailto, String subject, String body) throws AddressException, SendFailedException, MessagingException {

		if (webappAndMailHelper.isEmailFunctionalityDisabled()) return false;
		
		InternetAddress mailFromAddress = new InternetAddress(from);
		InternetAddress mailToAddress[] = InternetAddress.parse(mailto);
        MailerResult result = new MailerResult();
		
		MimeMessage msg = webappAndMailHelper.createMessage(mailFromAddress, mailToAddress, null, null, body + footer, subject, null, result);
		webappAndMailHelper.send(msg, result);
		//TODO:discuss why is the MailerResult not used here?
        return true;
    }
 
Example 4
Source File: ExceptionNotificationServiceImpl.java    From telekom-workflow-engine with MIT License 5 votes vote down vote up
private void sendEmail( String from, String to, String subject, String body ){
    log.info( "Sending exception email from:{} to:{} subject:{}", from, to, subject );
    try{
        Properties props = new Properties();
        props.put( "mail.smtp.host", smtpHost );
        if (StringUtils.isNotBlank(smtpPort)) {
            props.put( "mail.smtp.port", smtpPort );
        }
        Authenticator authenticator = null;
        if (StringUtils.isNotBlank(smtpUsername)) {
            props.put( "mail.smtp.auth", true );
            authenticator = new SmtpAuthenticator();
        }
        Session session = Session.getDefaultInstance( props, authenticator );

        Message msg = new MimeMessage( session );
        msg.setFrom( new InternetAddress( from ) );

        InternetAddress[] addresses = InternetAddress.parse( to );
        msg.setRecipients( Message.RecipientType.TO, addresses );

        msg.setSubject( subject );
        msg.setSentDate( new Date() );
        msg.setText( body );
        Transport.send( msg );
    }
    catch( Exception e ){
        log.warn( "Sending email failed: ", e );
    }
}
 
Example 5
Source File: ContactListTest.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void testContactListWithValidStringEmailsAddedIsConvertedToCorrectFormatsWithInstitutionalPrioFalse() throws AddressException {
    // Setup
    String simple = "Simple Name With Spaces";
    ContactList contactlist = new ContactList(simple);
    String helenEmail = ObjectMother.HELENE_MEYER_PRIVATE_EMAIL;
    String nioclasEmail = ObjectMother.NICOLAS_33_PRIVATE_EMAIL;
    String peterEmail = ObjectMother.PETER_BICHSEL_PRIVATE_EMAIL;

    // exercise
    contactlist.add(helenEmail);
    contactlist.add(nioclasEmail);
    contactlist.add(peterEmail);

    // verify all different email conversion and formatting of valid addresses
    verifyNameAndRFC2822NameFor(simple, contactlist);

    assertFalse("Institutional Email is not set", contactlist.isEmailPrioInstitutional());

    String expectedEmailString = ObjectMother.getEmailsAsCSVFor(helenEmail, nioclasEmail, peterEmail);
    String emailsAsCSV = contactlist.toString();
    assertEquals("emails as csv", expectedEmailString, emailsAsCSV);

    String expectedNameWithAddresses = simple + ":" + expectedEmailString + ";";
    assertEquals("RFC2822 Name with email addresses", expectedNameWithAddresses, contactlist.getRFC2822NameWithAddresses());

    InternetAddress[] expectedEmailsAsInetAdresses = InternetAddress.parse(expectedEmailString);
    InternetAddress[] emailsAsInetAdresses = contactlist.getEmailsAsAddresses();
    assertArrayEquals("emails als Interned Addresses", expectedEmailsAsInetAdresses, emailsAsInetAdresses);

    Hashtable<String, OLATPrincipal> identityEmails = contactlist.getIdentityEmails();
    assertNotNull("identity emails is not null", identityEmails);
    assertEquals("no identity emails are available", 0, identityEmails.size());
}
 
Example 6
Source File: MailSender.java    From tmxeditor8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 设置密送人,如果有多个密送人,用逗号分隔
 * @param bcc
 * 			密送人邮箱地址
 * @throws MessagingException
 * @throws EmailException ;
 */
public void setBCC(String bcc) throws MessagingException, EmailException {
	if (bcc == null) {
		return;
	}
	Address[] address = InternetAddress.parse(bcc);
	for (Address i : address) {
		Map<String, String> map = getEmailInfo(i.toString()); 
		email.addBcc(map.get("email"), map.get("name"));
	}
}
 
Example 7
Source File: SMTPAppender.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
InternetAddress[] parseAddress(String addressStr) {
  try {
    return InternetAddress.parse(addressStr, true);
  } catch(AddressException e) {
    errorHandler.error("Could not parse address ["+addressStr+"].", e,
	 ErrorCode.ADDRESS_PARSE_FAILURE);
    return null;
  }
}
 
Example 8
Source File: MailSender.java    From tmxeditor8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 设置回复人,如果有多个回复人,用逗号分隔
 * @param reply
 * @throws MessagingException
 * @throws EmailException ;
 */
public void setReplyTo(String reply) throws MessagingException, EmailException {
	if (reply == null) {
		return;
	}
	Address[] address = InternetAddress.parse(reply);
	for (Address i : address) {
		Map<String, String> map = getEmailInfo(i.toString()); 
		email.addReplyTo(map.get("email"), map.get("name"));
	}
}
 
Example 9
Source File: MimeMessageHelper.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private InternetAddress parseAddress(String address) throws MessagingException {
	InternetAddress[] parsed = InternetAddress.parse(address);
	if (parsed.length != 1) {
		throw new AddressException("Illegal address", address);
	}
	InternetAddress raw = parsed[0];
	try {
		return (getEncoding() != null ?
				new InternetAddress(raw.getAddress(), raw.getPersonal(), getEncoding()) : raw);
	}
	catch (UnsupportedEncodingException ex) {
		throw new MessagingException("Failed to parse embedded personal name to correct encoding", ex);
	}
}
 
Example 10
Source File: SMTPAppenderBase.java    From lemon with Apache License 2.0 5 votes vote down vote up
private List<InternetAddress> parseAddress(E event) {
    int len = toPatternLayoutList.size();

    List<InternetAddress> iaList = new ArrayList<InternetAddress>();

    for (int i = 0; i < len; i++) {
        try {
            PatternLayoutBase<E> emailPL = toPatternLayoutList.get(i);
            String emailAdrr = emailPL.doLayout(event);

            if ((emailAdrr == null) || (emailAdrr.length() == 0)) {
                continue;
            }

            InternetAddress[] tmp = InternetAddress.parse(emailAdrr, true);
            iaList.addAll(Arrays.asList(tmp));
        } catch (AddressException e) {
            addError("Could not parse email address for ["
                    + toPatternLayoutList.get(i) + "] for event [" + event
                    + "]", e);

            return iaList;
        }
    }

    return iaList;
}
 
Example 11
Source File: MailSender.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 设置抄送人,如果有多个抄送人,用逗号分隔
 * @param cc
 * 			抄送人邮箱地址
 * @throws MessagingException
 * @throws EmailException ;
 */
public void setCC(String cc) throws MessagingException, EmailException {
	if (cc == null) {
		return;
	}
	Address[] address = InternetAddress.parse(cc);
	for (Address i : address) {
		Map<String, String> map = getEmailInfo(i.toString()); 
		email.addCc(map.get("email"), map.get("name"));
	}
}
 
Example 12
Source File: Enviar_email.java    From redesocial with MIT License 5 votes vote down vote up
public static void main(String[] args) {
      Properties props = new Properties();
      /** Parâmetros de conexão com servidor Gmail */
      props.put("mail.smtp.host", "smtp.gmail.com");
      props.put("mail.smtp.socketFactory.port", "465");
      props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.port", "465");

      Session session = Session.getDefaultInstance(props,
                  new javax.mail.Authenticator() {
                       protected PasswordAuthentication getPasswordAuthentication() 
                       {
                             return new PasswordAuthentication("[email protected]", "tjm123456");
                       }
                  });
      /** Ativa Debug para sessão */
      session.setDebug(true);
      try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("[email protected]")); //Remetente

            Address[] toUser = InternetAddress //Destinatário(s)
                       .parse("[email protected]");  
            message.setRecipients(Message.RecipientType.TO, toUser);
            message.setSubject("Enviando email com JavaMail");//Assunto
            message.setText("Enviei este email utilizando JavaMail com minha conta GMail!");
            /**Método para enviar a mensagem criada*/
            Transport.send(message);
            System.out.println("Feito!!!");
       } catch (MessagingException e) {
            throw new RuntimeException(e);
      }
}
 
Example 13
Source File: MockMail.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
private void verifyAddress(String addr) {
    try {
        InternetAddress.parse(addr);
    }
    catch (AddressException e) {
        throw new RuntimeException("Bad address [" + addr + "]", e);
    }
}
 
Example 14
Source File: MailData.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
public void cmdRcptTo(String lineIn) {
  sizeRxd += lineIn.length();
  totalRxd += lineIn.length();

  try{
    InternetAddress[] address = InternetAddress.parse( lineIn.substring( lineIn.indexOf(":")+1 ) );
    
    boolean bAccept = false;
    for (int x=0; x<address.length;x++){
      bAccept = mail25.acceptMailTo( cfmailsession, address[x], getClientAddress() );
      if ( bAccept ){
        mailToList.add( new MailAddress( address[x] ) );
      }
    }

    if ( bAccept ){
      lastOutStatus = 250;
      lastOutMsg    = "Ok";
    }else{
      lastOutStatus = 550;
      lastOutMsg    = "No one here";
    }

  }catch (Exception e){
    lastOutStatus = 500;
    lastOutMsg    = "Bad Syntax (" + e.getMessage() + ")";
  }
}
 
Example 15
Source File: SimpleSmtpServerTest.java    From dumbster with Apache License 2.0 4 votes vote down vote up
@Test
public void testSendTwoMsgsWithLogin() throws Exception {
	String serverHost = "localhost";
	String from = "[email protected]";
	String to = "[email protected]";
	String subject = "Test";
	String body = "Test Body";

	Properties props = System.getProperties();

	if (serverHost != null) {
		props.setProperty("mail.smtp.host", serverHost);
	}

	Session session = Session.getDefaultInstance(props, null);
	Message msg = new MimeMessage(session);

	if (from != null) {
		msg.setFrom(new InternetAddress(from));
	} else {
		msg.setFrom();
	}

	InternetAddress.parse(to, false);
	msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
	msg.setSubject(subject);

	msg.setText(body);
	msg.setHeader("X-Mailer", "musala");
	msg.setSentDate(new Date());
	msg.saveChanges();

	Transport transport = null;

	try {
		transport = session.getTransport("smtp");
		transport.connect(serverHost, server.getPort(), "ddd", "ddd");
		transport.sendMessage(msg, InternetAddress.parse(to, false));
		transport.sendMessage(msg, InternetAddress.parse("[email protected]", false));
	} finally {
		if (transport != null) {
			transport.close();
		}
	}

	List<SmtpMessage> emails = this.server.getReceivedEmails();
	assertThat(emails, hasSize(2));
	SmtpMessage email = emails.get(0);
	assertTrue(email.getHeaderValue("Subject").equals("Test"));
	assertTrue(email.getBody().equals("Test Body"));
}
 
Example 16
Source File: MimeMessageBuilder.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
private static InternetAddress[] parseAddresses(final String addresses) throws AddressException {
    return addresses == null ? null : InternetAddress.parse(addresses, true);
}
 
Example 17
Source File: MailConnection.java    From scriptella-etl with Apache License 2.0 4 votes vote down vote up
/**
 * Creates an email connection.
 *
 * @param parameters connection parameters.
 */
public MailConnection(ConnectionParameters parameters) {
    super(Driver.DIALECT, parameters);
    String url = parameters.getUrl();
    if (StringUtils.isEmpty(url)) {
        throw new ConfigurationException("URL connection attribute is requred");
    }
    Matcher m = ADDRESS_PTR.matcher(url);
    if (!m.find()) {
        throw new ConfigurationException("URL connection attribute is not valid: " + url);
    }
    to = m.group(1).trim();
    if (to.length()==0) {
        throw new ConfigurationException("List of email addresses cannot be empty");
    }
    if (to.indexOf('$')>=0) { //Validate if mailto has no bind variable
        try {
            InternetAddress.parse(to, false);
        } catch (AddressException e) {
            throw new ConfigurationException("URL connection attribute must represent comma separated list of " +
                    "email addresses and follow RFC822 syntax: " + url, e);
        }
    }

    Properties properties = CollectionUtils.asProperties(parameters.getProperties());
    properties.putAll(parameters.getUrlQueryMap());
    type = properties.getProperty(TYPE);
    if (type != null && !type.equalsIgnoreCase(TYPE_TEXT) && !type.equalsIgnoreCase(TYPE_HTML)) {
        throw new ConfigurationException("Type parameter value must be one of text or html");
    }
    subject = properties.getProperty(SUBJECT);
    if (subject == null) {
        LOG.fine("EMail subject is not set for connection!");
    }

    session = Session.getInstance(properties);

    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Mail session initialized");
    }
}
 
Example 18
Source File: EmailNotificationService.java    From localization_nifi with Apache License 2.0 3 votes vote down vote up
/**
 * Creates an array of 0 or more InternetAddresses for the given String
 *
 * @param val the String to parse for InternetAddresses
 * @return an array of 0 or more InetAddresses
 * @throws AddressException if val contains an invalid address
 */
private static InternetAddress[] toInetAddresses(final String val) throws AddressException {
    if (val == null) {
        return new InternetAddress[0];
    }
    return InternetAddress.parse(val);
}
 
Example 19
Source File: MailMessage.java    From elexis-3-core with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Get the to address as {@link InternetAddress}.
 * 
 * @return
 * @throws AddressException
 */
public InternetAddress[] getToAddress() throws AddressException{
	return InternetAddress.parse(getTo());
}
 
Example 20
Source File: ContactList.java    From olat with Apache License 2.0 2 votes vote down vote up
/**
 * The e-mail addresses are generated as InternetAddresses, the priority of the institutional email is taken in account.
 * 
 * @return the email addresses as InternetAddresses
 * @throws AddressException
 */
public InternetAddress[] getEmailsAsAddresses() throws AddressException {
    return InternetAddress.parse(toString());
}