org.apache.commons.mail.EmailException Java Examples

The following examples show how to use org.apache.commons.mail.EmailException. 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: MailSenderDefaultImpl.java    From minsx-framework with Apache License 2.0 7 votes vote down vote up
public void finishInitial() {
    try {
        Integer sslPort = 465;
        simpleEmail = new SimpleEmail();
        simpleEmail.setHostName(this.host);
        simpleEmail.setSmtpPort(this.port);
        simpleEmail.setAuthentication(this.username, this.password);
        simpleEmail.setFrom(this.from);
        simpleEmail.setCharset("UTF-8");
        if (sslPort.equals(this.port)) {
            simpleEmail.setSSLOnConnect(true);
        }
        htmlEmail = new HtmlEmail();
        htmlEmail.setHostName(this.host);
        htmlEmail.setSmtpPort(this.port);
        htmlEmail.setAuthentication(this.username, this.password);
        htmlEmail.setFrom(this.from);
        htmlEmail.setCharset("UTF-8");
        if (sslPort.equals(this.port)) {
            htmlEmail.setSSLOnConnect(true);
        }
    } catch (EmailException e) {
        throw new MailSendException(String.format("Incorrect setting field of [from],cause: %s", e.getMessage()), e);
    }
}
 
Example #2
Source File: MailActivityBehavior.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void addTo(Email email, String to, String tenantId) {
    if (to == null) {
        // To has to be set, otherwise it can fallback to the forced To and then it won't be noticed early on
        throw new FlowableException("No recipient could be found for sending email");
    }
    String newTo = getForceTo(tenantId);
    if (newTo == null) {
        newTo = to;
    }
    String[] tos = splitAndTrim(newTo);
    if (tos != null) {
        for (String t : tos) {
            try {
                email.addTo(t);
            } catch (EmailException e) {
                throw new FlowableException("Could not add " + t + " as recipient", e);
            }
        }
    } else {
        throw new FlowableException("No recipient could be found for sending email");
    }
}
 
Example #3
Source File: EmailServiceTest.java    From AuthMeReloaded with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void shouldSendRecoveryCode() throws EmailException {
    // given
    given(settings.getProperty(SecuritySettings.RECOVERY_CODE_HOURS_VALID)).willReturn(7);
    given(settings.getRecoveryCodeEmailMessage())
        .willReturn("Hi <playername />, your code on <servername /> is <recoverycode /> (valid <hoursvalid /> hours)");
    HtmlEmail email = mock(HtmlEmail.class);
    given(sendMailSsl.initializeMail(anyString())).willReturn(email);
    given(sendMailSsl.sendEmail(anyString(), any(HtmlEmail.class))).willReturn(true);

    // when
    boolean result = emailService.sendRecoveryCode("Timmy", "[email protected]", "12C56A");

    // then
    assertThat(result, equalTo(true));
    verify(sendMailSsl).initializeMail("[email protected]");
    ArgumentCaptor<String> messageCaptor = ArgumentCaptor.forClass(String.class);
    verify(sendMailSsl).sendEmail(messageCaptor.capture(), eq(email));
    assertThat(messageCaptor.getValue(), equalTo("Hi Timmy, your code on serverName is 12C56A (valid 7 hours)"));
}
 
Example #4
Source File: EmailMessageSender.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private HtmlEmail getHtmlEmail( String hostName, int port, String username, String password, boolean tls,
    String sender ) throws EmailException
{
    HtmlEmail email = new HtmlEmail();
    email.setHostName( hostName );
    email.setFrom( sender, getEmailName() );
    email.setSmtpPort( port );
    email.setStartTLSEnabled( tls );

    if ( username != null && password != null )
    {
        email.setAuthenticator( new DefaultAuthenticator( username, password ) );
    }

    return email;
}
 
Example #5
Source File: EmailServiceThrowingException.java    From estatio with Apache License 2.0 6 votes vote down vote up
private boolean sendMessage(
        final ImageHtmlEmail email, final int backoffIntervalMs, final int numBackoffIntervals) {
    try {
        email.send();
        return true;
    } catch (EmailException ex) {

        if(backoffIntervalMs == 0) {
            LOG.error(String.format(
                        "Failed to send an email after %d attempts; giving up", numBackoffIntervals),
                      ex);
            throw new RuntimeException(ex);
        }

        LOG.warn(String.format(
                    "Failed to send an email; sleeping for %d seconds then will retry", backoffIntervalMs),
                 ex);
        sleep(backoffIntervalMs);
        return false;
    }
}
 
Example #6
Source File: Mail.java    From restcommander with Apache License 2.0 6 votes vote down vote up
/**
 *
 */
public static Email buildMessage(Email email) throws EmailException {

    String from = Play.configuration.getProperty("mail.smtp.from");
    if (email.getFromAddress() == null && !StringUtils.isEmpty(from)) {
        email.setFrom(from);
    } else if (email.getFromAddress() == null) {
        throw new MailException("Please define a 'from' email address", new NullPointerException());
    }
    if ((email.getToAddresses() == null || email.getToAddresses().size() == 0) &&
        (email.getCcAddresses() == null || email.getCcAddresses().size() == 0)  &&
        (email.getBccAddresses() == null || email.getBccAddresses().size() == 0)) 
    {
        throw new MailException("Please define a recipient email address", new NullPointerException());
    }
    if (email.getSubject() == null) {
        throw new MailException("Please define a subject", new NullPointerException());
    }
    if (email.getReplyToAddresses() == null || email.getReplyToAddresses().size() == 0) {
        email.addReplyTo(email.getFromAddress().getAddress());
    }

    return email;
}
 
Example #7
Source File: Util.java    From JARVIS with MIT License 6 votes vote down vote up
public static void takePicture() throws FileNotFoundException, IOException, EmailException {
	Webcam webcam = null;
	String filePath = null;
	try{
	Properties pro = getProperties();
	filePath = pro.getProperty("RobotWorkPlace")+"CamPic/Pic";
	webcam = Webcam.getDefault();
       webcam.setViewSize(WebcamResolution.VGA.getSize());
       WebcamPanel panel = new WebcamPanel(webcam);
       panel.setFPSDisplayed(true);
       panel.setDisplayDebugInfo(true);
       panel.setImageSizeDisplayed(true);
       panel.setMirrored(true);
       WebcamUtils.capture(webcam, filePath, ImageUtils.FORMAT_PNG);
	}finally{
		webcam.close();
	}
       MailUtil.sendPic("Camera", filePath+".png");
}
 
Example #8
Source File: MailActivityBehavior.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void addTo(CommandContext commandContext, Email email, String to, String tenantId) {
    if (to == null) {
        // To has to be set, otherwise it can fallback to the forced To and then it won't be noticed early on
        throw new FlowableException("No recipient could be found for sending email");
    }
    String newTo = getForceTo(commandContext, tenantId);
    if (newTo == null) {
        newTo = to;
    }
    String[] tos = splitAndTrim(newTo);
    if (tos != null) {
        for (String t : tos) {
            try {
                email.addTo(t);
            } catch (EmailException e) {
                throw new FlowableException("Could not add " + t + " as recipient", e);
            }
        }
    } else {
        throw new FlowableException("No recipient could be found for sending email");
    }
}
 
Example #9
Source File: MailActivityBehavior.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void addCc(CommandContext commandContext, Email email, String cc, String tenantId) {
    if (cc == null) {
        return;
    }

    String newCc = getForceTo(commandContext, tenantId);
    if (newCc == null) {
        newCc = cc;
    }
    String[] ccs = splitAndTrim(newCc);
    if (ccs != null) {
        for (String c : ccs) {
            try {
                email.addCc(c);
            } catch (EmailException e) {
                throw new FlowableException("Could not add " + c + " as cc recipient", e);
            }
        }
    }
}
 
Example #10
Source File: MailActivityBehavior.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void addBcc(CommandContext commandContext, Email email, String bcc, String tenantId) {
    if (bcc == null) {
        return;
    }
    String newBcc = getForceTo(commandContext, tenantId);
    if (newBcc == null) {
        newBcc = bcc;
    }
    String[] bccs = splitAndTrim(newBcc);
    if (bccs != null) {
        for (String b : bccs) {
            try {
                email.addBcc(b);
            } catch (EmailException e) {
                throw new FlowableException("Could not add " + b + " as bcc recipient", e);
            }
        }
    }
}
 
Example #11
Source File: SendMailSslTest.java    From AuthMeReloaded with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void shouldCreateEmailObjectWithOAuth2() throws EmailException {
    // given
    given(settings.getProperty(EmailSettings.SMTP_PORT)).willReturn(587);
    given(settings.getProperty(EmailSettings.OAUTH2_TOKEN)).willReturn("oAuth2 token");
    String smtpHost = "mail.example.com";
    given(settings.getProperty(EmailSettings.SMTP_HOST)).willReturn(smtpHost);
    String senderMail = "[email protected]";
    given(settings.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn(senderMail);

    // when
    HtmlEmail email = sendMailSsl.initializeMail("[email protected]");

    // then
    assertThat(email, not(nullValue()));
    assertThat(email.getToAddresses(), hasSize(1));
    assertThat(email.getToAddresses().get(0).getAddress(), equalTo("[email protected]"));
    assertThat(email.getFromAddress().getAddress(), equalTo(senderMail));
    assertThat(email.getHostName(), equalTo(smtpHost));
    assertThat(email.getSmtpPort(), equalTo("587"));

    Properties mailProperties = email.getMailSession().getProperties();
    assertThat(mailProperties.getProperty("mail.smtp.auth.mechanisms"), equalTo("XOAUTH2"));
    assertThat(mailProperties.getProperty("mail.smtp.auth.plain.disable"), equalTo("true"));
    assertThat(mailProperties.getProperty(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP), equalTo("oAuth2 token"));
}
 
Example #12
Source File: MailActivityBehavior.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void setFrom(Email email, String from, String tenantId) {
    String fromAddress = null;

    if (from != null) {
        fromAddress = from;
    } else { // use default configured from address in process engine config
        if (tenantId != null && tenantId.length() > 0) {
            Map<String, MailServerInfo> mailServers = CommandContextUtil.getProcessEngineConfiguration().getMailServers();
            if (mailServers != null && mailServers.containsKey(tenantId)) {
                MailServerInfo mailServerInfo = mailServers.get(tenantId);
                fromAddress = mailServerInfo.getMailServerDefaultFrom();
            }
        }

        if (fromAddress == null) {
            fromAddress = CommandContextUtil.getProcessEngineConfiguration().getMailServerDefaultFrom();
        }
    }

    try {
        email.setFrom(fromAddress);
    } catch (EmailException e) {
        throw new FlowableException("Could not set " + from + " as from address in email", e);
    }
}
 
Example #13
Source File: MailSenderDefaultImpl.java    From minsx-framework with Apache License 2.0 6 votes vote down vote up
@Override
public void sendHtmlMail(List<String> to, String title, String htmlText, List<EmailAttachment> emailAttachments) {
    finishInitial();
    try {
        htmlEmail.setSubject(title);
        for (String t : to) {
            simpleEmail.addBcc(t);
        }
        htmlEmail.setHtmlMsg(htmlText);
        htmlEmail.setSentDate(new Date());
        for (EmailAttachment emailAttachment : emailAttachments) {
            htmlEmail.attach(emailAttachment);
        }
        htmlEmail.send();
    } catch (EmailException e) {
        throw new MailSendException(String.format("Send Email [%s] failed,cause: %s", title, e.getMessage()), e);
    }
}
 
Example #14
Source File: Mailer.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
public void send(String recipient, String subject, String body) {
    new Thread(() -> {
        try {
            HtmlEmail email = new HtmlEmail();
            email.setHostName(config.getHost());
            email.setSmtpPort(config.getPort());
            email.setAuthenticator(new DefaultAuthenticator(config.getUsername(), config.getPassword()));
            email.setSSLOnConnect(config.getUseSsl());
            email.setFrom(config.getSender());
            email.setSubject(subject);
            email.setHtmlMsg(body);
            email.addTo(recipient);
            email.send();
        } catch (EmailException e) {
            throw new RuntimeException(e);
        }
    }).start();
}
 
Example #15
Source File: EmailHelper.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
public static void sendNotificationForDataIncomplete(
    Multimap<String, DataCompletenessConfigDTO> incompleteEntriesToNotify, ThirdEyeAnomalyConfiguration thirdeyeConfig) {
  HtmlEmail email = new HtmlEmail();
  String subject = String.format("Data Completeness Checker Report");
  StringBuilder textBody = new StringBuilder();
  for (String dataset : incompleteEntriesToNotify.keySet()) {
    List<DataCompletenessConfigDTO> entries = Lists.newArrayList(incompleteEntriesToNotify.get(dataset));
    textBody.append(String.format("\nDataset: %s\n", dataset));
    for (DataCompletenessConfigDTO entry : entries) {
      textBody.append(String.format("%s ", entry.getDateToCheckInSDF()));
    }
    textBody.append("\n*******************************************************\n");
  }
  LOG.info("Data Completeness Checker Report : Sending email to {} with subject {} and text {}",
      thirdeyeConfig.getFailureToAddress(), subject, textBody.toString());

  try {
    EmailHelper.sendEmailWithTextBody(email,
        SmtpConfiguration.createFromProperties(thirdeyeConfig.getAlerterConfiguration().get(SMTP_CONFIG_KEY)),
        subject, textBody.toString(), thirdeyeConfig.getFailureFromAddress(),
        new DetectionAlertFilterRecipients(EmailUtils.getValidEmailAddresses(thirdeyeConfig.getFailureToAddress())));
  } catch (EmailException e) {
    LOG.error("Exception in sending email notification for incomplete datasets", e);
  }

}
 
Example #16
Source File: ForgotPasswordController.java    From mamute with Apache License 2.0 6 votes vote down vote up
@Post
public void requestEmailWithToken(String email) {
	User user = users.loadByEmail(email);

	if (user == null) {
		validator.add(messageFactory.build("error", "forgot_password.invalid_email"));
		validator.onErrorRedirectTo(this).forgotPasswordForm();
		return;
	}

	Email forgotPasswordEmail = emailWithTokenFor(user);
	try {
		mailer.send(forgotPasswordEmail);
		result.include("mamuteMessages", Arrays.asList(
					messageFactory.build("confirmation", "forgot_password.sent_mail", user.getEmail()),
					messageFactory.build("confirmation", "forgot_password.sent_mail.warn")
				));
		result.redirectTo(this).forgotPasswordForm();
	} catch (EmailException e) {
		validator.add(messageFactory.build("error", "forgot_password.send_mail.error"));
		validator.onErrorRedirectTo(this).forgotPasswordForm();
	}	
}
 
Example #17
Source File: MailActivityBehavior.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void setFrom(Email email, String from, String tenantId) {
    String fromAddress = null;

    if (from != null) {
        fromAddress = from;
    } else { // use default configured from address in process engine config
        if (tenantId != null && tenantId.length() > 0) {
            Map<String, MailServerInfo> mailServers = Context.getProcessEngineConfiguration().getMailServers();
            if (mailServers != null && mailServers.containsKey(tenantId)) {
                MailServerInfo mailServerInfo = mailServers.get(tenantId);
                fromAddress = mailServerInfo.getMailServerDefaultFrom();
            }
        }

        if (fromAddress == null) {
            fromAddress = Context.getProcessEngineConfiguration().getMailServerDefaultFrom();
        }
    }

    try {
        email.setFrom(fromAddress);
    } catch (EmailException e) {
        throw new ActivitiException("Could not set " + from + " as from address in email", e);
    }
}
 
Example #18
Source File: SendMailSslTest.java    From AuthMeReloaded with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void shouldCreateEmailObjectWithAddress() throws EmailException {
    // given
    given(settings.getProperty(EmailSettings.SMTP_PORT)).willReturn(465);
    String smtpHost = "mail.example.com";
    given(settings.getProperty(EmailSettings.SMTP_HOST)).willReturn(smtpHost);
    String senderAccount = "exampleAccount";
    given(settings.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn(senderAccount);
    String senderAddress = "[email protected]";
    given(settings.getProperty(EmailSettings.MAIL_ADDRESS)).willReturn(senderAddress);
    String senderName = "Server administration";
    given(settings.getProperty(EmailSettings.MAIL_SENDER_NAME)).willReturn(senderName);

    // when
    HtmlEmail email = sendMailSsl.initializeMail("[email protected]");

    // then
    assertThat(email, not(nullValue()));
    assertThat(email.getToAddresses(), hasSize(1));
    assertThat(email.getToAddresses().get(0).getAddress(), equalTo("[email protected]"));
    assertThat(email.getFromAddress().getAddress(), equalTo(senderAddress));
    assertThat(email.getFromAddress().getPersonal(), equalTo(senderName));
    assertThat(email.getHostName(), equalTo(smtpHost));
    assertThat(email.getSmtpPort(), equalTo("465"));
}
 
Example #19
Source File: EmailService.java    From AuthMeReloaded with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Sends an email to the user with the temporary verification code.
 *
 * @param name the name of the player
 * @param mailAddress the player's email
 * @param code the verification code
 * @return true if email could be sent, false otherwise
 */
public boolean sendVerificationMail(String name, String mailAddress, String code) {
    if (!hasAllInformation()) {
        logger.warning("Cannot send verification email: not all email settings are complete");
        return false;
    }

    HtmlEmail email;
    try {
        email = sendMailSsl.initializeMail(mailAddress);
    } catch (EmailException e) {
        logger.logException("Failed to create verification email with the given settings:", e);
        return false;
    }

    String mailText = replaceTagsForVerificationEmail(settings.getVerificationEmailMessage(), name, code,
        settings.getProperty(SecuritySettings.VERIFICATION_CODE_EXPIRATION_MINUTES));
    return sendMailSsl.sendEmail(mailText, email);
}
 
Example #20
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 #21
Source File: MailActivityBehavior.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected HtmlEmail createHtmlEmail(String text, String html) {
    HtmlEmail email = new HtmlEmail();
    try {
        email.setHtmlMsg(html);
        if (text != null) { // for email clients that don't support html
            email.setTextMsg(text);
        }
        return email;
    } catch (EmailException e) {
        throw new ActivitiException("Could not create HTML email", e);
    }
}
 
Example #22
Source File: EmailConfigurationApiResourceTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testEmailConfigurationSendsTestEmail() throws EmailException {
  when(emailConfiguration.isEnabled()).thenReturn(true);
  when(emailManager.getConfiguration()).thenReturn(emailConfiguration);
  String destinationAddress = "[email protected]";

  underTest.testEmailConfiguration(destinationAddress);

  verify(emailManager).sendVerification(emailConfiguration, destinationAddress);
}
 
Example #23
Source File: MailActivityBehavior.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
protected HtmlEmail createHtmlEmail(String text, String html) {
  HtmlEmail email = new HtmlEmail();
  try {
    email.setHtmlMsg(html);
    if (text != null) { // for email clients that don't support html
      email.setTextMsg(text);
    }
    return email;
  } catch (EmailException e) {
    throw LOG.emailCreationException("HTML", e);
  }
}
 
Example #24
Source File: EmailManagerImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void send(final Email mail) throws EmailException {
  checkNotNull(mail);

  EmailConfiguration model = getConfigurationInternal();
  if (model.isEnabled()) {
    Email prepared = apply(model, mail);
    prepared.send();
  }
  else {
    log.warn("No email enabled but asked to send anyway.");
  }
}
 
Example #25
Source File: MailSender.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 设置要发送的附件
 * @param attachment
 * 				附件数组
 * @throws MessagingException
 * @throws UnsupportedEncodingException
 * @throws EmailException ;
 */
public void setMixMail(File[] attachment) throws MessagingException, UnsupportedEncodingException, EmailException {
	if (attachment != null) {
		for (File file : attachment) {
			EmailAttachment attach = new EmailAttachment();
			attach.setPath(file.getAbsolutePath());
			attach.setName(MimeUtility.encodeText(file.getName()));
			email.attach(attach);
		}
	}
}
 
Example #26
Source File: EmailHelper.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
/** Sends email according to the provided config. */
private static void sendEmail(SmtpConfiguration config, HtmlEmail email, String subject,
    String fromAddress, DetectionAlertFilterRecipients recipients) throws EmailException {
  if (config != null) {
    email.setSubject(subject);
    LOG.info("Sending email to {}", recipients.toString());
    email.setHostName(config.getSmtpHost());
    email.setSmtpPort(config.getSmtpPort());
    if (config.getSmtpUser() != null && config.getSmtpPassword() != null) {
      email.setAuthenticator(
          new DefaultAuthenticator(config.getSmtpUser(), config.getSmtpPassword()));
      email.setSSLOnConnect(true);
    }
    email.setFrom(fromAddress);
    email.setTo(AlertUtils.toAddress(recipients.getTo()));
    if (CollectionUtils.isNotEmpty(recipients.getCc())) {
      email.setCc(AlertUtils.toAddress(recipients.getCc()));
    }
    if (CollectionUtils.isNotEmpty(recipients.getBcc())) {
      email.setBcc(AlertUtils.toAddress(recipients.getBcc()));
    }
    email.send();
    LOG.info("Email sent with subject [{}] to address [{}]!", subject, recipients.toString());
  } else {
    LOG.error("No email config provided for email with subject [{}]!", subject);
  }
}
 
Example #27
Source File: SendEmail.java    From sAINT with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void sendEmailAttachment(String email_to, String assunto, String msg, String file, String file_logs) {
    File fileScreenshot = new File(file);
    EmailAttachment attachment = new EmailAttachment();
    attachment.setPath(fileScreenshot.getPath());
    attachment.setDisposition(EmailAttachment.ATTACHMENT);
    attachment.setDescription("Attachment");
    attachment.setName(fileScreenshot.getName());

    File fileLogs = new File(file_logs);
    EmailAttachment attachmentLogs = new EmailAttachment();
    attachmentLogs.setPath(fileLogs.getPath());
    attachmentLogs.setDisposition(EmailAttachment.ATTACHMENT);
    attachmentLogs.setDescription("Logs");
    attachmentLogs.setName(fileLogs.getName());

    try {
        MultiPartEmail email = new MultiPartEmail();
        email.setDebug(debug);
        email.setHostName(smtp);
        email.addTo(email_to);
        email.setFrom(email_from);
        email.setAuthentication(email_from, email_password);
        email.setSubject(assunto);
        email.setMsg(msg);
        email.setSSL(true);
        email.attach(attachment);
        email.attach(attachmentLogs);
        email.send();
    } catch (EmailException e) {
        System.out.println(e.getMessage());
    }
}
 
Example #28
Source File: MailSender.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 设置要发送的附件,并对附件重命名
 * @param attachment
 * 				附件的集合,key 为附件的名称,value为附件
 * @throws MessagingException
 * @throws UnsupportedEncodingException
 * @throws EmailException ;
 */
public void setMixMailRename(Map<String, File> attachment) throws MessagingException, UnsupportedEncodingException,
		EmailException {
	if (attachment != null) {
		for (String fileName : attachment.keySet()) {
			EmailAttachment attach = new EmailAttachment();
			attach.setPath(attachment.get(fileName).getAbsolutePath());
			attach.setName(MimeUtility.encodeText(fileName));
			email.attach(attach);
		}
	}
}
 
Example #29
Source File: MailTest.java    From restcommander with Apache License 2.0 5 votes vote down vote up
@Test(expected = MailException.class)
public void buildMessageWithoutSubject() throws EmailException {
	new PlayBuilder().build();

	Email email = new SimpleEmail();
	email.setFrom("[email protected]");
	email.addTo("[email protected]");
	Mail.buildMessage(email);
}
 
Example #30
Source File: MailSenderDefaultImpl.java    From minsx-framework with Apache License 2.0 5 votes vote down vote up
@Override
public void sendHtmlMail(List<String> to, String title, String htmlText) {
    finishInitial();
    try {
        htmlEmail.setSubject(title);
        for (String t : to) {
            simpleEmail.addBcc(t);
        }
        htmlEmail.setHtmlMsg(htmlText);
        htmlEmail.setSentDate(new Date());
        htmlEmail.send();
    } catch (EmailException e) {
        throw new MailSendException(String.format("Send Email [%s] failed,cause: %s", title, e.getMessage()), e);
    }
}