javax.mail.Address Java Examples

The following examples show how to use javax.mail.Address. 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: MailServerImpl.java    From webcurator with Apache License 2.0 6 votes vote down vote up
public void send(Mailable email) throws MessagingException {
    Session mailSession = Session.getInstance(this.mailConfig, null);
    Message message = new MimeMessage(mailSession);

    message.setFrom(new InternetAddress(email.getSender()));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(email.getRecipients()));
    setUpCCandBCC(email, message);

    if(email.getReplyTo()!=null && email.getReplyTo().trim().length()!=0) {
        message.setReplyTo(new Address[] {new InternetAddress(email.getReplyTo())});
    }

    message.setSubject(email.getSubject());
    message.setSentDate(new Date());
    message.setContent(email.getMessage(), "text/plain; charset=UTF-8");

    Transport.send(message); 
}
 
Example #2
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 #3
Source File: SpitterMailServiceImplTest.java    From Project with Apache License 2.0 6 votes vote down vote up
@Test
public void sendSimpleSpittleEmail() throws Exception {
	Spitter spitter = new Spitter(1L, "habuma", null, "Craig Walls", "[email protected]", true);
	Spittle spittle = new Spittle(1L, spitter, "Hiya!", new Date());
	mailService.sendSimpleSpittleEmail("[email protected]", spittle);

	MimeMessage[] receivedMessages = mailServer.getReceivedMessages();
	assertEquals(1, receivedMessages.length);
	assertEquals("New spittle from Craig Walls", receivedMessages[0].getSubject());
	assertEquals("Craig Walls says: Hiya!", ((String) receivedMessages[0].getContent()).trim());
	Address[] from = receivedMessages[0].getFrom();
	assertEquals(1, from.length);
	assertEquals("[email protected]", ((InternetAddress) from[0]).getAddress());
	assertEquals("[email protected]",
			((InternetAddress) receivedMessages[0].getRecipients(RecipientType.TO)[0]).getAddress());
}
 
Example #4
Source File: Pop3Util.java    From anyline with Apache License 2.0 6 votes vote down vote up
/**  
   * 获得邮件发件人  
   * @param msg 邮件内容  
   * @return 姓名 <Email地址>  
   */   
  public static String getFrom(MimeMessage msg){   
      String from = "";   
      Address[] froms; 
try { 
	froms = msg.getFrom(); 
       InternetAddress address = (InternetAddress) froms[0];   
       String person = address.getPersonal();   
       if (person != null) {   
           person = MimeUtility.decodeText(person) + " ";   
       } else {   
           person = "";   
       }   
       from = person + "<" + address.getAddress() + ">";   
} catch (Exception e) { 
	e.printStackTrace(); 
}   
      return from;   
  }
 
Example #5
Source File: ContentModelMessage.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * This method builds {@link MimeMessage} based on {@link ContentModel}
 * 
 * @throws MessagingException
 */
private void buildContentModelMessage() throws MessagingException
{
    Map<QName, Serializable> properties = messageFileInfo.getProperties();
    String prop = null;
    setSentDate(messageFileInfo.getModifiedDate());
    // Add FROM address
    Address[] addressList = buildSenderFromAddress();
    addFrom(addressList);
    // Add TO address
    addressList = buildRecipientToAddress();
    addRecipients(RecipientType.TO, addressList);
    prop = (String) properties.get(ContentModel.PROP_TITLE);
    try
    {
        prop = (prop == null || prop.equals("")) ? messageFileInfo.getName() : prop;
        prop = MimeUtility.encodeText(prop, AlfrescoImapConst.UTF_8, null);
    }
    catch (UnsupportedEncodingException e)
    {
        // ignore
    }
    setSubject(prop);
    setContent(buildContentModelMultipart());
}
 
Example #6
Source File: MailDelivrerTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
public void deliverShouldWorkIfOnlyMX2Valid() throws Exception {
    Mail mail = FakeMail.builder().name("name").recipients(MailAddressFixture.ANY_AT_JAMES, MailAddressFixture.OTHER_AT_JAMES).build();
    Address[] validSent = {};
    Address[] validUnsent = {new InternetAddress(MailAddressFixture.OTHER_AT_JAMES.asString())};
    Address[] invalid = {};
    SendFailedException sfe = new SendFailedException("Message",
        new Exception(),
        validSent,
        validUnsent,
        invalid);

    UnmodifiableIterator<HostAddress> dnsEntries = ImmutableList.of(
        HOST_ADDRESS_1,
        HOST_ADDRESS_2).iterator();
    when(dnsHelper.retrieveHostAddressIterator(MailAddressFixture.JAMES_APACHE_ORG)).thenReturn(dnsEntries);
    when(mailDelivrerToHost.tryDeliveryToHost(any(Mail.class), any(Collection.class), eq(HOST_ADDRESS_1)))
        .thenThrow(sfe);
    when(mailDelivrerToHost.tryDeliveryToHost(any(Mail.class), any(Collection.class), eq(HOST_ADDRESS_2)))
        .thenReturn(ExecutionResult.success());
    ExecutionResult executionResult = testee.deliver(mail);

    verify(mailDelivrerToHost, times(2)).tryDeliveryToHost(any(Mail.class), any(Collection.class), any(HostAddress.class));
    assertThat(executionResult.getExecutionState()).isEqualTo(ExecutionResult.ExecutionState.SUCCESS);
}
 
Example #7
Source File: SpitterMailServiceImplTest.java    From Project with Apache License 2.0 6 votes vote down vote up
public void receiveTest() throws Exception {
	MimeMessage[] receivedMessages = mailServer.getReceivedMessages();
	assertEquals(1, receivedMessages.length);
	assertEquals("New spittle from Craig Walls", receivedMessages[0].getSubject());
	Address[] from = receivedMessages[0].getFrom();
	assertEquals(1, from.length);
	assertEquals("[email protected]", ((InternetAddress) from[0]).getAddress());
	assertEquals(toEmail,
			((InternetAddress) receivedMessages[0].getRecipients(RecipientType.TO)[0]).getAddress());

	MimeMultipart multipart = (MimeMultipart) receivedMessages[0].getContent();
	Part part = null;
	for(int i=0;i<multipart.getCount();i++) {
		part = multipart.getBodyPart(i);
		System.out.println(part.getFileName());
		System.out.println(part.getSize());
	}
}
 
Example #8
Source File: JamesMailetContext.java    From james-project with Apache License 2.0 6 votes vote down vote up
/**
 * Place a mail on the spool for processing
 *
 * @param message the message to send
 * @throws MessagingException if an exception is caught while placing the mail on the spool
 */
@Override
public void sendMail(MimeMessage message) throws MessagingException {
    MailAddress sender = new MailAddress((InternetAddress) message.getFrom()[0]);
    Collection<MailAddress> recipients = new HashSet<>();
    Address[] addresses = message.getAllRecipients();
    if (addresses != null) {
        for (Address address : addresses) {
            // Javamail treats the "newsgroups:" header field as a
            // recipient, so we want to filter those out.
            if (address instanceof InternetAddress) {
                recipients.add(new MailAddress((InternetAddress) address));
            }
        }
    }
    sendMail(sender, recipients, message);
}
 
Example #9
Source File: JavamailService.java    From teammates with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public MimeMessage parseToEmail(EmailWrapper wrapper) throws MessagingException, IOException {
    Session session = Session.getDefaultInstance(new Properties(), null);
    MimeMessage email = new MimeMessage(session);
    if (wrapper.getSenderName() == null || wrapper.getSenderName().isEmpty()) {
        email.setFrom(new InternetAddress(wrapper.getSenderEmail()));
    } else {
        email.setFrom(new InternetAddress(wrapper.getSenderEmail(), wrapper.getSenderName()));
    }
    email.setReplyTo(new Address[] { new InternetAddress(wrapper.getReplyTo()) });
    email.addRecipient(Message.RecipientType.TO, new InternetAddress(wrapper.getRecipient()));
    if (wrapper.getBcc() != null && !wrapper.getBcc().isEmpty()) {
        email.addRecipient(Message.RecipientType.BCC, new InternetAddress(wrapper.getBcc()));
    }
    email.setSubject(wrapper.getSubject());
    email.setContent(wrapper.getContent(), "text/html");
    return email;
}
 
Example #10
Source File: MailDelivrerTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
public void handleSenderFailedExceptionShouldSetRecipientToValidUnsentWhenValidUnsentAndInvalid() throws Exception {
    Mail mail = FakeMail.builder().name("name").recipients(MailAddressFixture.ANY_AT_JAMES, MailAddressFixture.OTHER_AT_JAMES).build();

    Address[] validSent = {};
    Address[] validUnsent = {new InternetAddress(MailAddressFixture.OTHER_AT_JAMES.asString())};
    Address[] invalid = {new InternetAddress(MailAddressFixture.ANY_AT_JAMES.asString())};
    SendFailedException sfe = new SendFailedException("Message",
        new Exception(),
        validSent,
        validUnsent,
        invalid);
    testee.handleSenderFailedException(mail, sfe);

    assertThat(mail.getRecipients()).containsOnly(MailAddressFixture.OTHER_AT_JAMES);
}
 
Example #11
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 #12
Source File: EmailNotificationPluginImplUnitTest.java    From email-notifier with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipleEmailAddressSendsEmail() throws Exception {
    settingsResponseMap.put("receiver_email_id", "[email protected], [email protected]");

    GoApiResponse settingsResponse = testSettingsResponse();

    when(goApplicationAccessor.submit(any(GoApiRequest.class))).thenReturn(settingsResponse);
    doCallRealMethod().when(mockSession).createMessage(anyString(), anyString(), anyString(), anyString());

    GoPluginApiRequest requestFromServer = testStageChangeRequestFromServer();

    emailNotificationPlugin.handle(requestFromServer);

    verify(mockTransport).sendMessage(any(Message.class), eq(new Address[]{new InternetAddress("[email protected]")}));
    verify(mockTransport).sendMessage(any(Message.class), eq(new Address[]{new InternetAddress("[email protected]")}));
    verify(mockTransport, times(2)).connect(eq("test-smtp-host"), eq(25), eq("test-smtp-username"), eq("test-smtp-password"));
    verify(mockTransport, times(2)).close();
    verifyNoMoreInteractions(mockTransport);
}
 
Example #13
Source File: TransportTest.java    From javamail with Apache License 2.0 6 votes vote down vote up
@Test
public void testListenerOnSuccess() throws Exception {
    Address[] to = new Address[] {new InternetAddress("[email protected]")};
    Message message = generateMessage();
    TransportListener transportListener = Mockito.mock(TransportListener.class);
    AbstractFileTransport transport = (AbstractFileTransport) session.getTransport("filemsg");
    transport.addTransportListener(transportListener);
    transport.sendMessage(message, to);
    waitForListeners();
    ArgumentCaptor<TransportEvent> transportEventArgumentCaptor = ArgumentCaptor.forClass(TransportEvent.class);
    verify(transportListener).messageDelivered(transportEventArgumentCaptor.capture());
    TransportEvent event = transportEventArgumentCaptor.getValue();
    assertEquals(message, event.getMessage());
    assertEquals(TransportEvent.MESSAGE_DELIVERED, event.getType());
    assertArrayEquals(to, event.getValidSentAddresses());
    verify(transportListener).messageDelivered(any(TransportEvent.class));
}
 
Example #14
Source File: RecipientTerm.java    From FairEmail with GNU General Public License v3.0 6 votes vote down vote up
/**
    * The match method.
    *
    * @param msg	The address match is applied to this Message's recepient
    *			address
    * @return		true if the match succeeds, otherwise false
    */
   @Override
   public boolean match(Message msg) {
Address[] recipients;

try {
	    recipients = msg.getRecipients(type);
} catch (Exception e) {
    return false;
}

if (recipients == null)
    return false;

for (int i=0; i < recipients.length; i++)
    if (super.match(recipients[i]))
	return true;
return false;
   }
 
Example #15
Source File: MailerWithTemplate.java    From olat with 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 #16
Source File: MessageHelper.java    From FairEmail with GNU General Public License v3.0 6 votes vote down vote up
static boolean equal(Address[] a1, Address[] a2) {
    if (a1 == null && a2 == null)
        return true;

    if (a1 == null || a2 == null)
        return false;

    if (a1.length != a2.length)
        return false;

    for (int i = 0; i < a1.length; i++)
        if (!a1[i].toString().equals(a2[i].toString()))
            return false;

    return true;
}
 
Example #17
Source File: JMS2JavaMailTest.java    From javamail with Apache License 2.0 6 votes vote down vote up
private static BytesMessage bytesMessageFor(MimeMessage mimeMessage, Address[] addresses) throws JMSException, IOException, MessagingException {
    mimeMessage.setContent("text", "plain/text");
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(out);
    oos.writeUTF("testProto");
    oos.writeObject(addresses == null ? new Address[0] : addresses);
    mimeMessage.writeTo(oos);
    BytesMessage message = Mockito.mock(BytesMessage.class);
    final ByteArrayInputStream messageBytes = new ByteArrayInputStream(out.toByteArray());
    when(message.readBytes(any(byte[].class))).thenAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
        return messageBytes.read((byte[]) invocation.getArguments()[0]);
        }
    });
    return message;
}
 
Example #18
Source File: SmtpAppenderTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testMessageFactorySetFrom() throws MessagingException {
    final MimeMessageBuilder builder = new MimeMessageBuilder(null);
    final String address = "[email protected]";

    assertNull(builder.build().getFrom());

    builder.setFrom(null);
    Address[] array = null;
    final Address addr = InternetAddress.getLocalAddress(null);
    if (addr != null) {
        array = new Address[] { addr };
    }
    assertArrayEquals(array, builder.build().getFrom());

    builder.setFrom(address);
    assertArrayEquals(new Address[] { new InternetAddress(address) },
            builder.build().getFrom());
}
 
Example #19
Source File: MailUtil.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Extracts the address email
 * 
 * @param a the address
 * @return the email
 */
public static String getAddressEmail(Address a) {
	if (a != null) {
		InternetAddress ia = (InternetAddress) a;
		return ia.getAddress();
	} else {
		return "";
	}
}
 
Example #20
Source File: Transport.java    From development with Apache License 2.0 5 votes vote down vote up
@Override
public void sendMessage(Message msg, Address[] addresses)
        throws MessagingException {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        msg.writeTo(out);
        lastMail = new String(out.toByteArray(), "UTF-8");
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example #21
Source File: MailAlert.java    From dble-docs-cn with GNU General Public License v2.0 5 votes vote down vote up
private boolean sendMail(boolean isResolve, ClusterAlertBean clusterAlertBean) {
    try {
        Properties props = new Properties();

        // 开启debug调试
        props.setProperty("mail.debug", "true");
        // 发送服务器需要身份验证
        props.setProperty("mail.smtp.auth", "true");
        // 设置邮件服务器主机名
        props.setProperty("mail.host", properties.getProperty(MAIL_SERVER));
        // 发送邮件协议名称
        props.setProperty("mail.transport.protocol", "smtp");

        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.socketFactory", sf);

        Session session = Session.getInstance(props);

        Message msg = new MimeMessage(session);
        msg.setSubject("DBLE告警 " + (isResolve ? "RESOLVE\n" : "ALERT\n"));
        StringBuilder builder = new StringBuilder();
        builder.append(groupMailMsg(clusterAlertBean, isResolve));
        msg.setText(builder.toString());
        msg.setFrom(new InternetAddress(properties.getProperty(MAIL_SENDER)));

        Transport transport = session.getTransport();
        transport.connect(properties.getProperty(MAIL_SERVER), properties.getProperty(MAIL_SENDER), properties.getProperty(SENDER_PASSWORD));

        transport.sendMessage(msg, new Address[]{new InternetAddress(properties.getProperty(MAIL_RECEIVE))});
        transport.close();
        //send EMAIL SUCCESS return TRUE
        return true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    //send fail reutrn false
    return false;
}
 
Example #22
Source File: SmtpMail.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
private void appendAddresses(StringBuffer buf, Address[] addrs) {
    if (addrs != null) {
        for (int x = 0; x < addrs.length; x++) {
            buf.append(addrs[x].toString());
            if (addrs.length > 1 && x < (addrs.length - 1)) {
                buf.append(",");
            }
        }
    }
}
 
Example #23
Source File: MailUtil.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Extracts the address name
 * 
 * @param a the address
 * 
 * @return the name
 */
public static String getAddressName(Address a) {
	if (a != null) {
		InternetAddress ia = (InternetAddress) a;

		if (ia.getPersonal() != null) {
			return ia.getPersonal();
		} else {
			return ia.getAddress();
		}
	} else {
		return "";
	}
}
 
Example #24
Source File: BasicEmailService.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * @param address The address, hopefully an {@link InternetAddress}
 * @return The email address if it can, otherwise the whole address.
 */
private String toEmail(Address address)
{
	if (address instanceof InternetAddress)
	{
		return ((InternetAddress) address).getAddress();
	}
	else
	{
		return address.toString();
	}
}
 
Example #25
Source File: MailUtils.java    From tmxeditor8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 过滤邮件中的 From 和 To,使邮件不允许发件人和收件人一样.
 * @param from
 * 			发件人集合
 * @param to
 * 			收件人集合
 * @return List&lt;Address>&gt;
 * 			收件人数组中过滤掉重复的发件人信息后剩余的集合。如果 from 为 null,返回 to;如果 to 为 null,返回 null
 */
public static List<Address> removeDuplicate(List<Address> from, List<Address> to) {
	if (from == null) {
		return to;
	}
	if (to == null) {
		return null;
	}
	Address[] fromArray = new Address[from.size()];
	Address[] toArray = new Address[to.size()];
	from.toArray(fromArray);
	to.toArray(toArray);
	Address[] result = removeDuplicate(fromArray, toArray);
	return Arrays.asList(result);
}
 
Example #26
Source File: MailSender.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 设置密送人,如果有多个密送人,用逗号分隔
 * @param bcc
 * 			密送人邮箱地址
 * @throws MessagingException
 * @throws EmailException ;
 */
public void setBCC(String bcc) throws MessagingException, EmailException {
	if (bcc == null) {
		return;
	}
	Address[] address = InternetAddress.parse(bcc);
	for (Address i : address) {
		Map<String, String> map = getEmailInfo(i.toString()); 
		email.addBcc(map.get("email"), map.get("name"));
	}
}
 
Example #27
Source File: SMTPNotifier.java    From juddi with Apache License 2.0 5 votes vote down vote up
public DispositionReport notifySubscriptionListener(NotifySubscriptionListener body) throws DispositionReportFaultMessage, RemoteException {

		

		try {
                        log.info("Sending notification email to " + notificationEmailAddress + " from " + getEMailProperties().getProperty("mail.smtp.from", "jUDDI"));
			if (session !=null && notificationEmailAddress != null) {
				MimeMessage message = new MimeMessage(session);
				InternetAddress address = new InternetAddress(notificationEmailAddress);
				Address[] to = {address};
				message.setRecipients(RecipientType.TO, to);
				message.setFrom(new InternetAddress(getEMailProperties().getProperty("mail.smtp.from", "jUDDI")));
				//maybe nice to use a template rather then sending raw xml.
				String subscriptionResultXML = JAXBMarshaller.marshallToString(body, JAXBMarshaller.PACKAGE_SUBSCR_RES);
				message.setText(subscriptionResultXML, "UTF-8");
                                //message.setContent(subscriptionResultXML, "text/xml; charset=UTF-8;");
				message.setSubject(ResourceConfig.getGlobalMessage("notifications.smtp.default.subject") + " " 
						+ StringEscapeUtils.escapeHtml(body.getSubscriptionResultsList().getSubscription().getSubscriptionKey()));
				Transport.send(message);
			}
                        else throw new DispositionReportFaultMessage("Session is null!", null);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			throw new DispositionReportFaultMessage(e.getMessage(), null);
		}

		DispositionReport dr = new DispositionReport();
		Result res = new Result();
		dr.getResult().add(res);

		return dr;
	}
 
Example #28
Source File: MimePackage.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Get all recipients from the specified type
 *
 * @param recipientType
 * @return
 * @throws PackageException
 */
@PublicAtsApi
public Address[] getRecipientAddresses(
                                        RecipientType recipientType ) throws PackageException {

    try {
        Address[] allAddresses = message.getRecipients(recipientType.toJavamailType());
        if (allAddresses == null) {
            allAddresses = new Address[0];
        }
        return allAddresses;
    } catch (MessagingException me) {
        throw new PackageException(me);
    }
}
 
Example #29
Source File: ICALToJsonAttribute.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Optional<MailAddress> retrieveSender(Mail mail) throws MessagingException {
    Optional<MailAddress> fromMime = StreamUtils.ofOptional(
        Optional.ofNullable(mail.getMessage())
            .map(Throwing.function(MimeMessage::getFrom).orReturn(new Address[]{})))
        .map(address -> (InternetAddress) address)
        .map(InternetAddress::getAddress)
        .map(MaybeSender::getMailSender)
        .flatMap(MaybeSender::asStream)
        .findFirst();

    return fromMime.or(() -> mail.getMaybeSender().asOptional());
}
 
Example #30
Source File: Test_SmtpSender.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
@Override
public void sendMessage(
                         Message arg0,
                         Address[] arg1 ) throws MessagingException {

    log.info("Fake message sending");

    if (deliveryState == DELIVERY_STATE.DELIVERED) {
        notifyTransportListeners(TransportEvent.MESSAGE_DELIVERED, null, null, null, null);
    } else if (deliveryState == DELIVERY_STATE.PARTIALLY_DELIVERED) {
        notifyTransportListeners(TransportEvent.MESSAGE_PARTIALLY_DELIVERED, null, null, null, null);
    } else if (deliveryState == DELIVERY_STATE.ERROR_DELIVERING) {
        notifyTransportListeners(TransportEvent.MESSAGE_NOT_DELIVERED, null, null, null, null);
    }
}