Java Code Examples for javax.mail.internet.AddressException

The following examples show how to use javax.mail.internet.AddressException. These examples are extracted from open source projects. 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 Project: omh-dsu-ri   Source File: EndUserServiceImpl.java    License: Apache License 2.0 7 votes vote down vote up
@Override
@Transactional
public void registerUser(EndUserRegistrationData registrationData) {

    if (doesUserExist(registrationData.getUsername())) {
        throw new EndUserRegistrationException(registrationData);
    }

    EndUser endUser = new EndUser();
    endUser.setUsername(registrationData.getUsername());
    endUser.setPasswordHash(passwordEncoder.encode(registrationData.getPassword()));
    endUser.setRegistrationTimestamp(OffsetDateTime.now());

    if (registrationData.getEmailAddress() != null) {
        try {
            endUser.setEmailAddress(new InternetAddress(registrationData.getEmailAddress()));
        }
        catch (AddressException e) {
            throw new EndUserRegistrationException(registrationData, e);
        }
    }

    endUserRepository.save(endUser);
}
 
Example 2
Source Project: olat   Source File: MailerWithTemplate.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Helper: creates an address array from a list of identities
 * 
 * @param recipients
 * @param result
 * @return Address array
 */
private Address[] createAddressesFromIdentities(List<? extends OLATPrincipal> recipients, MailerResult result) {
    Address[] addresses = null;
    if (recipients != null && recipients.size() > 0) {
        List<Address> validRecipients = new ArrayList<Address>();
        for (int i = 0; i < recipients.size(); i++) {
            OLATPrincipal principal = recipients.get(i);
            try {
                validRecipients.add(new InternetAddress(principal.getAttributes().getEmail()));
            } catch (AddressException e) {
                result.addFailedIdentites(principal);
            }
        }
        addresses = validRecipients.toArray(new Address[validRecipients.size()]);
    }
    return addresses;
}
 
Example 3
Source Project: olat   Source File: EmailerTest.java    License: Apache License 2.0 6 votes vote down vote up
private void caputureAndVerifyValuesForCreateMessage(List<ContactList> expectedRecipients, String expectedSubject, String expectedBody, List<File> expectedAttachments) throws AddressException, MessagingException {
	verify(webappAndMailhelperMockSystemMailer, times(1)).createMessage(fromCaptor.capture(), contactListCaptor.capture(), bodyCaptor.capture(), subjectCaptor.capture(), attachmentsCaptor.capture(), resultCaptor.capture());
	InternetAddress capturedFrom = fromCaptor.getValue();
	assertEquals("is olat admin email", ObjectMother.OLATADMIN_EMAIL, capturedFrom.getAddress());
	assertEquals("Emails in xyz are correct", expectedRecipients, contactListCaptor.getValue());
	assertEquals("subject", expectedSubject, subjectCaptor.getValue()); 
	assertEquals("body!", expectedBody, bodyCaptor.getValue());
	
	//this is Duplication of code inside Emailer, how to avoid?
	if(expectedAttachments == null || expectedAttachments.isEmpty()){
		assertArrayEquals("null attachements", null, attachmentsCaptor.getValue());
	}else{
		File[] tmp = new File[SIZE];
		assertArrayEquals("compare as arrays", expectedAttachments.toArray(tmp), attachmentsCaptor.getValue());
	}		
}
 
Example 4
Source Project: subethasmtp   Source File: EmailUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @return true if the string is a valid email address
 */
public static boolean isValidEmailAddress(String address)
{
	// MAIL FROM: <>
	if (address.length() == 0)
		return true;

	boolean result = false;
	try
	{
		InternetAddress[] ia = InternetAddress.parse(address, true);
		if (ia.length == 0)
			result = false;
		else
			result = true;
	}
	catch (AddressException ae)
	{
		result = false;
	}
	return result;
}
 
Example 5
Source Project: spacewalk   Source File: CreateUserCommand.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Private helper method to validate the user's email address. Puts errors into the
 * errors list.
 */
private void validateEmail() {
    // Make sure user and email are not null
    if (user == null || user.getEmail() == null) {
        errors.add(new ValidatorError("error.addr_invalid", "null"));
        return;
    }

    // Make email is not over the max length
    if (user.getEmail().length() > UserDefaults.get().getMaxEmailLength()) {
        errors.add(new ValidatorError("error.maxemail"));
        return;
    }

    // Make sure set email is valid
    try {
        new InternetAddress(user.getEmail()).validate();
    }
    catch (AddressException e) {
        errors.add(new ValidatorError("error.addr_invalid", user.getEmail()));
    }
}
 
Example 6
@Override
public void run() {
    checkClientId(arguments);
    int clientId = parseClientId(arguments.get(0));

    Warehouse warehouse = Warehouses.newDbWarehouse(clientId);

    List<ReportDelivery> reportDeliveries;
    try {
        reportDeliveries = createReportDeliveries(clientId);
    } catch (AddressException ex) {
        System.err.println("Wrong email address:" + ex.getMessage());
        System.exit(1);
        return;
    }

    new Web(arguments, dependencyFactory, warehouse, reportDeliveries).run();
    new Cli(arguments, dependencyFactory, warehouse, reportDeliveries).run();

    // INFO: Needed because when Cli exists the Web
    // interface's thread will keep the app hanging.
    System.exit(0);
}
 
Example 7
@Override
public void run() {
    checkClientId(arguments);
    int clientId = parseClientId(arguments.get(0));

    Warehouse warehouse = Warehouses.newDbWarehouse(clientId);

    List<ReportDelivery> reportDeliveries;
    try {
        reportDeliveries = createReportDeliveries(clientId);
    } catch (AddressException ex) {
        System.err.println("Wrong email address:" + ex.getMessage());
        System.exit(1);
        return;
    }

    new Web(arguments, dependencyFactory, warehouse, reportDeliveries).run();
    new Cli(arguments, dependencyFactory, warehouse, reportDeliveries).run();

    // INFO: Needed because when Cli exists the Web
    // interface's thread will keep the app hanging.
    System.exit(0);
}
 
Example 8
Source Project: Openfire   Source File: StringUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns true if the string passed in is a valid Email address.
 *
 * @param address Email address to test for validity.
 * @return true if the string passed in is a valid email address.
 */
public static boolean isValidEmailAddress(String address) {
    if (address == null) {
        return false;
    }

    if (!address.contains("@")) {
        return false;
    }

    try {
        InternetAddress.parse(address);
        return true;
    }
    catch (AddressException e) {
        return false;
    }
}
 
Example 9
Source Project: olat   Source File: ContactListTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testConversionToEmailAddressFormatsDoesNotFailWithoutEmailsAddedAndInstitutionalPrioTrue() throws AddressException {
    // Setup
    String simple = "Simple Name With Spaces";
    ContactList contactlist = new ContactList(simple);
    contactlist.setEmailPrioInstitutional(true);
    // exercise
    contactlist.getEmailsAsAddresses();
    contactlist.getEmailsAsStrings();
    contactlist.getIdentityEmails();
    contactlist.getRFC2822NameWithAddresses();
    // verify all different email conversion and formatting of valid addresses
    verifyNameAndRFC2822NameFor(simple, contactlist);

    assertTrue("Institutional Email is set", contactlist.isEmailPrioInstitutional());
}
 
Example 10
Source Project: mail-importer   Source File: CorruptEmailFixer.java    License: Apache License 2.0 6 votes vote down vote up
private boolean hasValidFrom(JavaxMailMessage message) {
  String[] fromHeaders = message.getHeader("From");
  Preconditions.checkState(fromHeaders.length == 1,
      "Expected exactly 1 From header, got: " + Arrays.toString(fromHeaders));
  String rawAddress = fromHeaders[0].replaceAll("\\s+"," ");
  try {
    InternetAddress[] address =
        InternetAddress.parseHeader(rawAddress, true);
    Preconditions.checkState(address.length == 1,
        "Expected exactly 1 From address, got: " + Arrays.toString(address));
    System.err.format("Valid? %s == %s\n", address[0].toString(), rawAddress);
    return address[0].toString().equals(rawAddress);
  } catch (AddressException e) {
    System.err.format("Not valid from because: %s", e.getMessage());
    return false;
  }
}
 
Example 11
Source Project: megatron-java   Source File: MailSender.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("null")
private InternetAddress[] parseAddresses(String addressesStr) throws AddressException {
    if (addressesStr == null) {
        throw new AddressException("Address is not assigned.");
    }

    String[] addresses = addressesStr.trim().split(";|,");
    if ((addresses == null) || (addresses.length == 0)) {
        new AddressException("Address is missing.");
    }

    List<InternetAddress> resultList = new ArrayList<InternetAddress>(addresses.length);
    for (int i = 0; i < addresses.length; i++) {
        String address = addresses[i].trim();
        if (address.length() > 0) {
            resultList.add(new InternetAddress(address));
        }
    }

    if (resultList.size() == 0) {
        new AddressException("Address is missing; result list is empty.");
    }

    return resultList.toArray(new InternetAddress[resultList.size()]);
}
 
Example 12
Source Project: BIMserver   Source File: MailSystem.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public static boolean isValidEmailAddress(String aEmailAddress) {
	if (aEmailAddress == null) {
		return false;
	}
	try {
		new InternetAddress(aEmailAddress);
		if (!hasNameAndDomain(aEmailAddress)) {
			return false;
		}
	} catch (AddressException ex) {
		return false;
	}
	return true;
}
 
Example 13
@POST
@Path("/verify")
@RequiresAuthentication
@RequiresPermissions("nexus:settings:update")
public ApiEmailValidation testEmailConfiguration(@NotNull String verificationAddress)
{
  EmailConfiguration emailConfiguration = emailManager.getConfiguration();

  if (emailConfiguration == null) {
    return new ApiEmailValidation(false, "Email Settings are not yet configured");
  }

  try {
    emailManager.sendVerification(emailConfiguration, verificationAddress);
    return new ApiEmailValidation(true);
  }
  catch (EmailException e) {
    log.debug("Unable to send verification", e);
    String exceptionMessage = e.getMessage().replace(e.getCause().getClass().getName() + ": ", "");
    if (e.getCause() instanceof AddressException) {
      throw new WebApplicationMessageException(BAD_REQUEST, '"' + exceptionMessage + '"', APPLICATION_JSON);
    }
    else {
      return new ApiEmailValidation(false, exceptionMessage);
    }
  }
}
 
Example 14
Source Project: greenmail   Source File: RcptCommand.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void execute(SmtpConnection conn, SmtpState state,
                    SmtpManager manager, String commandLine) {
    Matcher m = param.matcher(commandLine);

    try {
        if (m.matches()) {
            if (state.getMessage().getReturnPath() != null) {
                String to = m.group(1);

                MailAddress toAddr = new MailAddress(to);

                String err = manager.checkRecipient(state, toAddr);
                if (err != null) {
                    conn.send(err);

                    return;
                }

                state.getMessage().addRecipient(toAddr);
                conn.send("250 OK");
            } else {
                conn.send("503 MAIL must come before RCPT");
            }
        } else {
            conn.send("501 Required syntax: 'RCPT TO:<[email protected]>'");
        }
    } catch (AddressException e) {
        conn.send("501 Malformed email address. Use form [email protected]");
    }
}
 
Example 15
Source Project: james-project   Source File: MailCmdHandler.java    License: Apache License 2.0 5 votes vote down vote up
private MaybeSender toMaybeSender(String senderAsString) throws AddressException {
    if (senderAsString.length() == 0) {
        // This is the <> case.
        return MaybeSender.nullSender();
    }
    if (senderAsString.equals("@")) {
        return MaybeSender.nullSender();
    }
    return MaybeSender.of(new MailAddress(
        appendDefaultDomainIfNeeded(senderAsString)));
}
 
Example 16
Source Project: openemm   Source File: AgnUtils.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
private static InternetAddress asInternetAddress(String address) {
	try {
		return new InternetAddress(address);
	} catch (AddressException e) {
		throw new RuntimeException(e);
	}
}
 
Example 17
Source Project: gpmall   Source File: EmailConfig.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获得抄送地址
 * @return
 */
public Address[] getCcInternetAddress(){
    Address[] addresses = new Address[]{};
    List<InternetAddress> internetAddressList = new ArrayList<>();
    toAddresss.forEach(toAddress->{
        try {
            internetAddressList.add(new InternetAddress(toAddress));
        } catch (AddressException e) {
            e.printStackTrace();
        }
    });
    return (Address[]) internetAddressList.toArray(addresses);
}
 
Example 18
@Theory
public void shouldFailWithErrorWithAnyOtherMessagingException(final MessagingException me){
	//setup
	ExceptionHandlingMailSendingTemplate doSendWithSendFailedException = new ExceptionHandlingMailSendingTemplate() {
		@Override
		protected boolean doSend(Emailer emailer) throws AddressException, SendFailedException, MessagingException {
			assertNotNull("emailer was constructed", emailer);
			throw me;
		}
		
		@Override
		protected MailTemplate getMailTemplate() {
			return emptyMailTemplate;
		};
		
		@Override
		protected List<ContactList> getTheToContactLists() {
			return theContactLists;
		}
		
		@Override
		protected Identity getFromIdentity() {
			return theFromIdentity;
		}
	};
	
	//exercise
	MessageSendStatus sendStatus = doSendWithSendFailedException.send();					

	//verify
	assertEquals(MessageSendStatusCode.MAIL_CONTENT_NOK, sendStatus.getStatusCode());
	verifyStatusCodeIndicateMessagingExcpetionOnly(sendStatus);
	verifySendStatusIsWarn(sendStatus);
	assertFalse(sendStatus.canProceedWithWorkflow());
	
}
 
Example 19
Source Project: james-project   Source File: MockMessageHandler.java    License: Apache License 2.0 5 votes vote down vote up
private MailAddress parse(String mailAddress) {
    try {
        return new MailAddress(mailAddress);
    } catch (AddressException e) {
        LOGGER.error("Error parsing mail address '{}'", mailAddress, e);
        throw new RejectException(SMTPStatusCode.SYNTAX_ERROR_IN_PARAMETERS_OR_ARGUMENTS_501.getRawCode(), "invalid email address supplied");
    }
}
 
Example 20
Source Project: rice   Source File: EmailToList.java    License: Educational Community License v2.0 5 votes vote down vote up
public Address[] getToAddressesAsAddressArray() throws AddressException {
Address[] recipientAddresses = new Address[this.toAddresses.size()];
for (int i = 0; i < recipientAddresses.length; i++) {
    recipientAddresses[i] = new InternetAddress((String) this.toAddresses.get(i));
 }
       return recipientAddresses;
   }
 
Example 21
Source Project: gocd   Source File: ServerConfigService.java    License: Apache License 2.0 5 votes vote down vote up
public LocalizedOperationResult validateEmail(String email) {
    HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
    try {
        new InternetAddress(email, true);
    } catch (AddressException e) {
        result.notAcceptable("Not a valid email address.");
    }
    return result;
}
 
Example 22
/**
 * Inner method checking if email address is valid.
 *
 * @param email
 * @return
 */
private static boolean isValidEmail(String email) {
    try {
        InternetAddress emailAddr = new InternetAddress(email);
        emailAddr.validate();
        return true;
    } catch (AddressException e) {
        return false;
    }
}
 
Example 23
private static List<ReportDelivery> createReportDeliveries(int clientId) throws AddressException {
    List<ReportDelivery> result = new ArrayList<>();
    result.add(new NoReportDelivery());
    if (clientId == 1) {
        result.add(new EmailReportDelivery("[email protected]"));
        result.add(new DirectoryReportDelivery("."));
    } else {
        result.add(new DirectoryReportDelivery("."));
    }
    return result;
}
 
Example 24
public static void main(String[] args) {
    List<String> arguments = List.of(args);

    checkClientId(arguments);
    int clientId = parseClientId(arguments.get(0));

    Warehouse warehouse = Warehouses.newDbWarehouse(clientId);

    List<ReportDelivery> reportDeliveries;
    try {
        reportDeliveries = createReportDeliveries(clientId);
    } catch (AddressException ex) {
        System.err.println("Wrong email address:" + ex.getMessage());
        System.exit(1);
        return;
    }

    ExporterFactory exporterFactory = FULL_VERSION
        ? new FullExporterFactory()
        : new TrialExporterFactory();
    new Web(arguments, exporterFactory, warehouse, reportDeliveries).run();
    new Cli(arguments, exporterFactory, warehouse, reportDeliveries).run();

    // INFO: Needed because when Cli exists the Web
    // interface's thread will keep the app hanging.
    System.exit(0);
}
 
Example 25
Source Project: james-project   Source File: MailAddressTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testToInternetAddress() throws AddressException {
    InternetAddress b = new InternetAddress(GOOD_ADDRESS);
    MailAddress a = new MailAddress(b);

    assertThat(a.toInternetAddress()).isEqualTo(b);
    assertThat(a.toString()).isEqualTo(GOOD_ADDRESS);
}
 
Example 26
private static List<ReportDelivery> createReportDeliveries(int clientId) throws AddressException {
    List<ReportDelivery> result = new ArrayList<>();
    result.add(new NoReportDelivery());
    if (clientId == 1) {
        result.add(new EmailReportDelivery("[email protected]"));
        result.add(new DirectoryReportDelivery("."));
    } else {
        result.add(new DirectoryReportDelivery("."));
    }
    return result;
}
 
Example 27
Source Project: ShoppingCartinJava   Source File: ForgotPassword.java    License: MIT License 5 votes vote down vote up
public static void Send(final String username, final String password, String recipientEmail, String ccEmail, String title, String message) throws AddressException, MessagingException {
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

    // Get a Properties object
    Properties props = System.getProperties();
    props.setProperty("mail.smtps.host", "smtp.gmail.com");
    props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.setProperty("mail.smtp.socketFactory.fallback", "false");
    props.setProperty("mail.smtp.port", "465");
    props.setProperty("mail.smtp.socketFactory.port", "465");
    props.setProperty("mail.smtps.auth", "true");

    props.put("mail.smtps.quitwait", "false");

    Session session = Session.getInstance(props, null);

    // -- Create a new message --
    final MimeMessage msg = new MimeMessage(session);

    // -- Set the FROM and TO fields --
    msg.setFrom(new InternetAddress(username + "@gmail.com"));
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false));

    if (ccEmail.length() > 0) {
        msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false));
    }

    msg.setSubject(title);
    msg.setText(message, "utf-8");
    msg.setSentDate(new Date());

    SMTPTransport t = (SMTPTransport)session.getTransport("smtps");

    t.connect("smtp.gmail.com", username, password);
    t.sendMessage(msg, msg.getAllRecipients());      
    t.close();
}
 
Example 28
Source Project: occurrence   Source File: DownloadEmailUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Transforms a iterable of string into a list of email addresses.
 */
private static List<Address> toInternetAddresses(Iterable<String> strEmails) {
  List<Address> emails = Lists.newArrayList();
  for (String address : strEmails) {
    try {
      emails.add(new InternetAddress(address));
    } catch (AddressException e) {
      // bad address?
      LOG.warn("Ignore corrupt email address {}", address);
    }
  }
  return emails;
}
 
Example 29
Source Project: camunda-bpm-mail   Source File: MailTestUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static MimeMessage createMimeMessage(Session session) throws MessagingException, AddressException {
  MimeMessage message = new MimeMessage(session);

  message.setFrom(new InternetAddress("[email protected]"));
  message.addRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
  message.setSubject("subject");

  return message;
}
 
Example 30
Source Project: lemon   Source File: SMTPAppenderBase.java    License: Apache License 2.0 5 votes vote down vote up
InternetAddress getAddress(String addressStr) {
    try {
        return new InternetAddress(addressStr);
    } catch (AddressException e) {
        addError("Could not parse address [" + addressStr + "].", e);

        return null;
    }
}