javax.mail.internet.InternetAddress Java Examples

The following examples show how to use javax.mail.internet.InternetAddress. 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: SendEmailUtilsTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
private void verifyMessageSent(String... expectedRecipients) throws Exception {
  ArgumentCaptor<EmailMessage> contentCaptor = ArgumentCaptor.forClass(EmailMessage.class);
  verify(emailService).sendEmail(contentCaptor.capture());
  EmailMessage emailMessage = contentCaptor.getValue();
  ImmutableList.Builder<InternetAddress> recipientBuilder = ImmutableList.builder();
  for (String expectedRecipient : expectedRecipients) {
    recipientBuilder.add(new InternetAddress(expectedRecipient));
  }
  EmailMessage expectedContent =
      EmailMessage.newBuilder()
          .setSubject("Welcome to the Internet")
          .setBody("It is a dark and scary place.")
          .setFrom(new InternetAddress("[email protected]"))
          .setRecipients(recipientBuilder.build())
          .build();
  assertThat(emailMessage).isEqualTo(expectedContent);
}
 
Example #2
Source File: IcannReportingUploadActionTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccess_withRetry() throws Exception {
  IcannReportingUploadAction action = createAction();
  when(mockReporter.send(PAYLOAD_SUCCESS, "tld-transactions-200606.csv"))
      .thenThrow(new IOException("Expected exception."))
      .thenReturn(true);
  action.run();
  verify(mockReporter).send(PAYLOAD_SUCCESS, "foo-activity-200606.csv");
  verify(mockReporter).send(PAYLOAD_FAIL, "tld-activity-200606.csv");
  verify(mockReporter).send(PAYLOAD_SUCCESS, "foo-transactions-200606.csv");
  verify(mockReporter, times(2)).send(PAYLOAD_SUCCESS, "tld-transactions-200606.csv");
  verifyNoMoreInteractions(mockReporter);
  verify(emailService)
      .sendEmail(
          EmailMessage.create(
              "ICANN Monthly report upload summary: 3/4 succeeded",
              "Report Filename - Upload status:\n"
                  + "foo-activity-200606.csv - SUCCESS\n"
                  + "tld-activity-200606.csv - FAILURE\n"
                  + "foo-transactions-200606.csv - SUCCESS\n"
                  + "tld-transactions-200606.csv - SUCCESS",
              new InternetAddress("[email protected]"),
              new InternetAddress("[email protected]")));
}
 
Example #3
Source File: JMS2JavaMailTest.java    From javamail with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccessWithConnectedTransport() throws Exception {
    source.setSubject("msg subject");
    source.setFrom("[email protected]");
    source.setHeader("Header1", "Value1");
    BytesMessage message = bytesMessageFor(source, new Address[]{new InternetAddress("[email protected]")});
    Transport transport = Mockito.mock(Transport.class);
    when(transport.isConnected()).thenReturn(true);
    when(sessionDelegate.findTransport(eq("testProto"))).thenReturn(transport);
    jms2JavaMail.onMessage(message);
    verify(message, times(1)).acknowledge();
    verify(transport, never()).connect();
    verify(transport, never()).close();
    ArgumentCaptor<MimeMessage> mimeMessageArgumentCaptor = ArgumentCaptor.forClass(MimeMessage.class);
    ArgumentCaptor<Address[]> addressArgumentCaptor = ArgumentCaptor.forClass(Address[].class);
    verify(transport, times(1)).sendMessage(mimeMessageArgumentCaptor.capture(), addressArgumentCaptor.capture());
    MimeMessage dst = mimeMessageArgumentCaptor.getValue();
    InternetAddress toAddr = (InternetAddress) addressArgumentCaptor.getValue()[0];
    Assert.assertEquals("[email protected]", toAddr.getAddress());
    Assert.assertEquals(source.getSubject(), dst.getSubject());
    Assert.assertArrayEquals(source.getFrom(), dst.getFrom());
    Assert.assertArrayEquals(source.getHeader("Header1"), dst.getHeader("Header1"));
    verify(javaMailJMSStatistics, times(1)).onSuccess(any(MimeMessage.class), any(Address[].class));
    verify(javaMailJMSStatistics, never()).onFailure(any(MimeMessage.class), any(Address[].class), any(Exception.class));
}
 
Example #4
Source File: SESService.java    From hellokoding-courses with MIT License 6 votes vote down vote up
public boolean sendMail(String subject, String body) {
    try {
        Properties props = System.getProperties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.port", mailProperties.getSmtp().getPort());
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(props);

        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(mailProperties.getFrom(), mailProperties.getFromName()));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mailProperties.getTo()));
        msg.setSubject(subject);
        msg.setContent(body, "text/html");

        Transport transport = session.getTransport();
        transport.connect(mailProperties.getSmtp().getHost(), mailProperties.getSmtp().getUsername(), mailProperties.getSmtp().getPassword());
        transport.sendMessage(msg, msg.getAllRecipients());
        return true;
    } catch (Exception ex) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, ex.getMessage(), ex);
    }

    return false;
}
 
Example #5
Source File: EmailRendererConfigurationTest.java    From spring-boot-email-tools with Apache License 2.0 6 votes vote down vote up
private Email createEmailWithEmptyCustomHeaders() throws Exception {
    return DefaultEmail.builder()
            .from(new InternetAddress("[email protected]"))
            .to(null)
            .cc(null)
            .bcc(null)
            .replyTo(new InternetAddress("[email protected]"))
            .receiptTo(new InternetAddress("[email protected]"))
            .depositionNotificationTo(new InternetAddress("[email protected]"))
            .encoding("UTF-16")
            .locale(Locale.ITALY)
            .sentAt(SEND_AT_DATE)
            .subject("subject")
            .body("body")
            .customHeaders(ImmutableMap.of())
            .build();
}
 
Example #6
Source File: ComposeSimpleMessage.java    From java-course-ee with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        final Properties props = new Properties();
        props.load(ClassLoader.getSystemResourceAsStream("mail.properties"));

        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(props.getProperty("smtp.username"), props.getProperty("smtp.pass"));
            }
        });

        Message message = new MimeMessage(session);

        message.setFrom(new InternetAddress(props.getProperty("address.sender")));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(props.getProperty("address.recipient")));
        message.setSubject("Test JavaMail");

        message.setText("Hello!\n\n\tThis is a test message from JavaMail.\n\nThank you.");

        Transport.send(message);

        log.info("Message was sent");
    }
 
Example #7
Source File: BillingEmailUtilsTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccess_emailOverallInvoice() throws MessagingException {
  emailUtils.emailOverallInvoice();

  verify(emailService).sendEmail(contentCaptor.capture());
  EmailMessage emailMessage = contentCaptor.getValue();
  EmailMessage expectedContent =
      EmailMessage.newBuilder()
          .setFrom(new InternetAddress("[email protected]"))
          .setRecipients(
              ImmutableList.of(
                  new InternetAddress("[email protected]"), new InternetAddress("[email protected]")))
          .setSubject("Domain Registry invoice data 2017-10")
          .setBody("Attached is the 2017-10 invoice for the domain registry.")
          .setAttachment(
              Attachment.newBuilder()
                  .setContent("test,data\nhello,world")
                  .setContentType(MediaType.CSV_UTF_8)
                  .setFilename("REG-INV-2017-10.csv")
                  .build())
          .build();
  assertThat(emailMessage).isEqualTo(expectedContent);
}
 
Example #8
Source File: JavaMailSenderTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
public void testJavaMailSenderWithMimeMessage() throws MessagingException {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost("host");
	sender.setUsername("username");
	sender.setPassword("password");

	MimeMessage mimeMessage = sender.createMimeMessage();
	mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	sender.send(mimeMessage);

	assertEquals("host", sender.transport.getConnectedHost());
	assertEquals("username", sender.transport.getConnectedUsername());
	assertEquals("password", sender.transport.getConnectedPassword());
	assertTrue(sender.transport.isCloseCalled());
	assertEquals(1, sender.transport.getSentMessages().size());
	assertEquals(mimeMessage, sender.transport.getSentMessage(0));
}
 
Example #9
Source File: Mailer.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 6 votes vote down vote up
private static Message createMessage(Session session)
        throws MessagingException, IOException {
    Message msg = new MimeMessage(session);
    InternetAddress fromAddress = new InternetAddress(
            getVal("from.mail"), getVal("username"));
    msg.setFrom(fromAddress);
    Optional.ofNullable(getVal("to.mail")).ifPresent((String tos) -> {
        for (String to : tos.split(";")) {
            try {
                msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
                        to, to));
            } catch (Exception ex) {
                Logger.getLogger(Mailer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });

    msg.setSubject(parseSubject(getVal("msg.subject")));
    msg.setContent(getMessagePart());
    return msg;
}
 
Example #10
Source File: JavaMailSenderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void javaMailSenderWithParseExceptionOnMimeMessagePreparator() {
	MockJavaMailSender sender = new MockJavaMailSender();
	MimeMessagePreparator preparator = new MimeMessagePreparator() {
		@Override
		public void prepare(MimeMessage mimeMessage) throws MessagingException {
			mimeMessage.setFrom(new InternetAddress(""));
		}
	};
	try {
		sender.send(preparator);
	}
	catch (MailParseException ex) {
		// expected
		assertTrue(ex.getCause() instanceof AddressException);
	}
}
 
Example #11
Source File: MailClient.java    From ankush with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Converts addresses in List<String> to InternetAddress array.
 *
 * @param addressLst a List<String> where each item in list corresponds to one mail
 * address
 * @return returns array of corresponding InternetAddress for the provided
 * List<String> argument
 */
private InternetAddress[] getInternetAddress(List<String> addressLst) {
	int size = 0;
	if (addressLst != null) {
		size = addressLst.size();
	}
	InternetAddress[] address = new InternetAddress[size];
	for (int i = 0; i < size; i++) {
		try {
			address[i] = new InternetAddress(addressLst.get(i));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
	return address;
}
 
Example #12
Source File: TransportTest.java    From javamail with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws AddressException, IOException {
    String outDirName = "target/output";
    Properties properties = new Properties();
    outDir = new File(outDirName);
    if (outDir.exists()) {
        File[] files = outDir.listFiles();
        if (files != null) {
            for (File f : files) {
                if (! f.delete()) {
                    Logger.getLogger(getClass().getName()).log(Level.WARNING, "Unable to delete test file " + f.getAbsolutePath());
                }
            }
        }
    }
    properties.put("mail.files.path", outDirName);
    session = Session.getDefaultInstance(properties);
    toAddress = new Address[] { new InternetAddress("[email protected]") };
    outputStream = new ByteArrayOutputStream();
}
 
Example #13
Source File: EmailToMimeMessageTest.java    From spring-boot-email-tools with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldIgnoreNullTo() throws Exception {
    //Arrange
    when(javaMailSender.createMimeMessage()).thenReturn(new MimeMessage((Session) null));

    final DefaultEmail email = DefaultEmail.builder()
            .from(getCiceroMainMailAddress())
            .replyTo(getCiceroSecondayMailAddress())
            .cc(Lists.newArrayList(new InternetAddress("[email protected]", "Titus Lucretius Carus"),
                    new InternetAddress("[email protected]", "Info Best Seller")))
            .bcc(Lists.newArrayList(new InternetAddress("[email protected]", "Caius Memmius")))
            .depositionNotificationTo(new InternetAddress("[email protected]", "Gaius Iulius Caesar Augustus Germanicus"))
            .receiptTo(new InternetAddress("[email protected]", "Gaius Iulius Caesar Augustus Germanicus"))
            .subject("Laelius de amicitia")
            .body("Firmamentum autem stabilitatis constantiaeque eius, quam in amicitia quaerimus, fides est.")
            .customHeaders(CUSTOM_HEADERS)
            .build();


    //Act
    MimeMessage message = emailToMimeMessage.apply(email);

    //Assert
    assertions.assertThat(message.getRecipients(Message.RecipientType.TO)).isNullOrEmpty();
}
 
Example #14
Source File: EmailTest.java    From commons-email with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddCc2() throws Exception
{
    // ====================================================================
    // Test Success
    // ====================================================================

    final String[] testEmailNames = {"Name1", "", null};

    final List<InternetAddress> arrExpected = new ArrayList<InternetAddress>();
    arrExpected.add(new InternetAddress("[email protected]", "Name1"));
    arrExpected.add(new InternetAddress("[email protected]"));
    arrExpected.add(new InternetAddress("[email protected]"));

    for (int i = 0; i < VALID_EMAILS.length; i++)
    {
        // set from
        email.addCc(VALID_EMAILS[i], testEmailNames[i]);
    }

    // retrieve and verify
    assertEquals(arrExpected.size(), email.getCcAddresses().size());
    assertEquals(arrExpected.toString(), email.getCcAddresses().toString());
}
 
Example #15
Source File: MimePackage.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
/**
 * This method resturns only the email address portion of the sender
 * contained in the first From header
 *
 * @return the sender address
 * @throws PackageException
 */
@PublicAtsApi
public String getSenderAddress() throws PackageException {

    try {
        Address[] fromAddresses = message.getFrom();
        if (fromAddresses == null || fromAddresses.length == 0) {
            throw new PackageException("Sender not present");
        }

        InternetAddress fromAddress = (InternetAddress) fromAddresses[0];
        return fromAddress.getAddress();

    } catch (MessagingException me) {
        throw new PackageException(me);
    }
}
 
Example #16
Source File: JavaMailSenderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void javaMailSenderWithMimeMessage() throws MessagingException {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost("host");
	sender.setUsername("username");
	sender.setPassword("password");

	MimeMessage mimeMessage = sender.createMimeMessage();
	mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	sender.send(mimeMessage);

	assertEquals("host", sender.transport.getConnectedHost());
	assertEquals("username", sender.transport.getConnectedUsername());
	assertEquals("password", sender.transport.getConnectedPassword());
	assertTrue(sender.transport.isCloseCalled());
	assertEquals(1, sender.transport.getSentMessages().size());
	assertEquals(mimeMessage, sender.transport.getSentMessage(0));
}
 
Example #17
Source File: SendEmailController.java    From oncokb with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Create a MimeMessage using the parameters provided.
 *
 * @param to Email address of the receiver.
 * @param from Email address of the sender, the mailbox account.
 * @param subject Subject of the email.
 * @param bodyText Body text of the email.
 * @return MimeMessage to be used to send email.
 * @throws MessagingException
 */
private static MimeMessage createEmail(String to, String from, String subject,
                                       String bodyText) throws MessagingException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);
    InternetAddress tAddress = new InternetAddress(to);
    InternetAddress fAddress = new InternetAddress(from);

    email.setFrom(new InternetAddress(from));
    email.addRecipient(javax.mail.Message.RecipientType.TO,
            new InternetAddress(to));
    email.setSubject(subject);
    email.setText(bodyText);
    return email;
}
 
Example #18
Source File: DefaultEmailSender.java    From gpmall with Apache License 2.0 5 votes vote down vote up
@Override
public void doSendHtmlMailUseTemplate(MailData mailData) throws Exception {
    /**创建一个邮件的会话**/
    Authenticator authenticator = null;
    if (emailConfig.isMailSmtpAuth()) {//如果需要身份认证,则创建一个密码验证器
        authenticator =  new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return  new PasswordAuthentication(emailConfig.getUsername(),emailConfig.getPassword());
            }
        };
    }
    Session session = Session.getDefaultInstance(emailConfig.getProperties(),authenticator);
    /**创建邮件信心**/
    Message message = new MimeMessage(session);
    //发送地址
    message.setFrom(new InternetAddress(emailConfig.getFromAddress()));
    //发送邮件给自己,解决发送邮件554的问题
    message.addRecipients(Message.RecipientType.CC ,new Address[]{new InternetAddress(emailConfig.getFromAddress())});
    //接收地址
    message.addRecipients(Message.RecipientType.TO ,mailData.getToInternetAddress());
    //抄送地址
    message.addRecipients(Message.RecipientType.CC ,mailData.getCcInternetAddress());
    //邮件主题
    message.setSubject(mailData.getSubject());
    //邮件内容
    Multipart multipart = new MimeMultipart();
    BodyPart bodyPart = new MimeBodyPart();
    String content = FreeMarkerUtil.getMailTextForTemplate(emailConfig.getTemplatePath(),mailData.getFileName(),mailData.getDataMap());
    bodyPart.setContent(content,mailData.getContent_type());
    multipart.addBodyPart(bodyPart);
    message.setContent(multipart);
    message.setSentDate(new Date());
    //发送邮件
    Transport.send(message);
}
 
Example #19
Source File: TestListenSMTP.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testListenSMTP() throws Exception {
    final ListenSMTP processor = new ListenSMTP();
    final TestRunner runner = TestRunners.newTestRunner(processor);

    final int port = NetworkUtils.availablePort();
    runner.setProperty(ListenSMTP.SMTP_PORT, String.valueOf(port));
    runner.setProperty(ListenSMTP.SMTP_MAXIMUM_CONNECTIONS, "3");

    runner.run(1, false);

    assertTrue(String.format("expected server listening on %s:%d", "localhost", port), NetworkUtils.isListening("localhost", port, 5000));

    final Properties config = new Properties();
    config.put("mail.smtp.host", "localhost");
    config.put("mail.smtp.port", String.valueOf(port));
    config.put("mail.smtp.connectiontimeout", "5000");
    config.put("mail.smtp.timeout", "5000");
    config.put("mail.smtp.writetimeout", "5000");

    final Session session = Session.getInstance(config);
    session.setDebug(true);

    final int numMessages = 5;
    for (int i = 0; i < numMessages; i++) {
        final Message email = new MimeMessage(session);
        email.setFrom(new InternetAddress("[email protected]"));
        email.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));
        email.setSubject("This is a test");
        email.setText("MSG-" + i);
        Transport.send(email);
    }

    runner.shutdown();
    runner.assertAllFlowFilesTransferred(ListenSMTP.REL_SUCCESS, numMessages);
}
 
Example #20
Source File: EmailFormatterInbound.java    From matrix-appservice-email with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Optional<_EmailBridgeMessage> get(String key, Message msg) {
    try {
        String sender = ((InternetAddress) msg.getFrom()[0]).getAddress(); // TODO sanitize properly
        log.info("Email is from {}", sender);

        if (Objects.isNull(msg.getSentDate())) {
            // As per https://tools.ietf.org/html/rfc5322#page-19
            log.warn("Email is illegal, Date info missing. Skipping");
            return Optional.empty();
        }

        List<_BridgeMessageContent> contents = extractContent(msg);
        if (contents.isEmpty()) {
            log.warn("Found no valid content, skipping");
            return Optional.empty();
        }

        for (_EmailClientFormatter f : clientFormatters) {
            if (f.matches(msg, contents)) {
                log.info("Using inbound formatter {}", f.getId());

                List<_BridgeMessageContent> contentFormatted = new ArrayList<>();
                for (_BridgeMessageContent content : contents) {
                    contentFormatted.add(f.format(content));
                }
                contents = contentFormatted;
                break;
            } else {
                log.info("Inbound formatter {} did not match", f.getId());
            }
        }

        return Optional.of(new EmailBridgeMessage(key, msg.getSentDate().toInstant(), sender, contents));
    } catch (IOException | MessagingException e) {
        throw new RuntimeException(e);
    }
}
 
Example #21
Source File: MailComponent.java    From awacs with Apache License 2.0 5 votes vote down vote up
Group(String[] addr) {
    this.recipients = new Address[addr.length];
    for (int i = 0; i < addr.length; i++) {
        try {
            this.recipients[i] = new InternetAddress(addr[i]);
        } catch (AddressException e) {
            e.printStackTrace();
        }
    }
}
 
Example #22
Source File: DefaultEmailSender.java    From gpmall with Apache License 2.0 5 votes vote down vote up
@Override
public void doHtmlSend(MailData mailData) throws Exception {
    /**创建一个邮件的会话**/
    Authenticator authenticator = null;
    if (emailConfig.isMailSmtpAuth()) {//如果需要身份认证,则创建一个密码验证器
        authenticator =  new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return  new PasswordAuthentication(emailConfig.getUsername(),emailConfig.getPassword());
            }
        };
    }
    Session session = Session.getDefaultInstance(emailConfig.getProperties(),authenticator);
    /**创建邮件信心**/
    Message message = new MimeMessage(session);
    //发送地址
    message.setFrom(new InternetAddress(emailConfig.getFromAddress()));
    //发送邮件给自己,解决发送邮件554的问题
    message.addRecipients(Message.RecipientType.CC ,new Address[]{new InternetAddress(emailConfig.getFromAddress())});
    //接收地址
    message.addRecipients(Message.RecipientType.TO ,mailData.getToInternetAddress());
    //抄送地址
    message.addRecipients(Message.RecipientType.CC ,mailData.getCcInternetAddress());
    //邮件主题
    message.setSubject(mailData.getSubject());
    //邮件内容
    Multipart multipart = new MimeMultipart();
        BodyPart bodyPart = new MimeBodyPart();
        bodyPart.setContent(mailData.getContent(),mailData.getContent_type());
    multipart.addBodyPart(bodyPart);
    message.setContent(multipart);
    message.setSentDate(new Date());
    //发送邮件
    Transport.send(message);

}
 
Example #23
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 #24
Source File: AbstractMailSenderFactory.java    From nano-framework with Apache License 2.0 5 votes vote down vote up
/**
 * 以HTML格式发送邮件.
 *
 * @param mailSender 待发送的邮件信息
 * @return Boolean
 */
protected boolean sendHtmlMail(final AbstractMailSender mailSender) {
    final Properties pro = mailSender.getProperties();
    MailAuthenticator authenticator = null;
    if (mailSender.isValidate()) {
        authenticator = new MailAuthenticator(mailSender.getUserName(), mailSender.getPassword());
    }

    final Session sendMailSession;
    if(singletonSessionInstance) {
        sendMailSession = Session.getDefaultInstance(pro, authenticator);
    } else {
        sendMailSession = Session.getInstance(pro, authenticator);
    }
    
    sendMailSession.setDebug(debugEnabled);
    try {
        final Message mailMessage = new MimeMessage(sendMailSession);
        final Address from = new InternetAddress(mailSender.getFromAddress());
        mailMessage.setFrom(from);
        mailMessage.setRecipients(Message.RecipientType.TO, toAddresses(mailSender.getToAddress()));
        mailMessage.setSubject(mailSender.getSubject());
        mailMessage.setSentDate(new Date());
        final Multipart mainPart = new MimeMultipart();
        final BodyPart html = new MimeBodyPart();
        html.setContent(mailSender.getContent(), "text/html; charset=utf-8");
        mainPart.addBodyPart(html);
        mailMessage.setContent(mainPart);
        Transport.send(mailMessage);
        return true;
    } catch (final MessagingException ex) {
        LOGGER.error(ex.getMessage(), ex);
    }
    
    return false;
}
 
Example #25
Source File: SessionWrapper.java    From email-notifier with Apache License 2.0 5 votes vote down vote up
public MimeMessage createMessage(String fromEmailId, String toEmailId, String subject, String body) throws MessagingException {
    MimeMessage message = new MimeMessage(instance);
    message.setFrom(new InternetAddress(fromEmailId));
    message.setRecipients(TO, toEmailId);
    message.setSubject(subject);
    message.setContent(message, "text/plain");
    message.setSentDate(new Date());
    message.setText(body);
    message.setSender(new InternetAddress(fromEmailId));
    message.setReplyTo(new InternetAddress[]{new InternetAddress(fromEmailId)});
    return message;
}
 
Example #26
Source File: MailSender.java    From difido-reports with Apache License 2.0 5 votes vote down vote up
private InternetAddress[] getAddresses(String[] addresses) throws AddressException {
	if (addresses == null) {
		return new InternetAddress[0];
	}

	InternetAddress[] internetAaddresses = new InternetAddress[addresses.length];
	for (int i = 0; i < addresses.length; i++) {
		internetAaddresses[i] = new InternetAddress(addresses[i]);
	}
	return internetAaddresses;
}
 
Example #27
Source File: AddressExtractor.java    From james-project with Apache License 2.0 5 votes vote down vote up
private List<MailAddress> extract(Optional<String> maybeAddressList) throws MessagingException {
    if (!maybeAddressList.isPresent()) {
        return ImmutableList.of();
    }
    String addressList = maybeAddressList.get();
    try {
        return toMailAddresses(ImmutableList.copyOf(InternetAddress.parse(addressList, ENFORCE_RFC822_SYNTAX)));
    } catch (AddressException e) {
        throw new MessagingException("Exception thrown parsing: " + addressList, e);
    }
}
 
Example #28
Source File: RhnValidationHelper.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return <code>true</code> if <code>email</code> is a valid email
 * address
 * @param email the email to validate
 * @return <code>true</code> if <code>email</code> is a valid email
 * address
 * @see InternetAddress#validate
 */
public static boolean isValidEmailAddress(String email) {
    try {
        new InternetAddress(email).validate();
        return true;
    }
    catch (AddressException e) {
        return false;
    }
}
 
Example #29
Source File: EmailName.java    From jweb-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
public Address toAddress() throws AddressException, UnsupportedEncodingException {
    if (username == null) {
        return new InternetAddress(email);
    } else {
        return new InternetAddress(email, username);
    }
}
 
Example #30
Source File: BasicEmailService.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void sendMail(InternetAddress from, InternetAddress[] to, String subject, String content, InternetAddress[] headerTo,
		InternetAddress[] replyTo, List<String> additionalHeaders)
{
	HashMap<RecipientType, InternetAddress[]> recipients = null;
	if (headerTo != null)
	{
		recipients = new HashMap<RecipientType, InternetAddress[]>();
		recipients.put(RecipientType.TO, headerTo);
	}
	sendMail(from, to, subject, content, recipients, replyTo, additionalHeaders, null);
}