下面列出了怎么用javax.mail.internet.AddressException的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
}
/**
* 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;
}
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());
}
}
/**
* @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;
}
/**
* 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()));
}
}
@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);
}
@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);
}
/**
* 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;
}
}
@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());
}
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;
}
}
@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()]);
}
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;
}
@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);
}
}
}
@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]");
}
}
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)));
}
private static InternetAddress asInternetAddress(String address) {
try {
return new InternetAddress(address);
} catch (AddressException e) {
throw new RuntimeException(e);
}
}
/**
* 获得抄送地址
* @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);
}
@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());
}
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");
}
}
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;
}
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;
}
/**
* 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;
}
}
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;
}
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);
}
@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);
}
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;
}
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();
}
/**
* 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;
}
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;
}
InternetAddress getAddress(String addressStr) {
try {
return new InternetAddress(addressStr);
} catch (AddressException e) {
addError("Could not parse address [" + addressStr + "].", e);
return null;
}
}