Java Code Examples for javax.mail.MessagingException

The following examples show how to use javax.mail.MessagingException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: ats-framework   Source File: MimePackage.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Return the attachment data
 *
 * @param partIndex
 *            the index of the attachment
 * @return an InputStream with the attachment data
 * @throws PackageException
 */
@PublicAtsApi
public InputStream getAttachmentPartData(
                                          int partIndex ) throws PackageException {

    try {
        boolean storeReconnected = reconnectStoreIfClosed();
        // store should be opened for actions including getting InputStream. Hence store open is not in getPart
        try {
            MimePart part = getPart(partIndex, true);
            return part.getInputStream();
        } finally {
            closeStoreConnection(storeReconnected);
        }
    } catch (MessagingException me) {
        throw new PackageException("Error getting attachment data for part " + partIndex, me);
    } catch (IOException ioe) {
        throw new PackageException("Error getting attachment data for part " + partIndex, ioe);
    }
}
 
Example 2
Source Project: spring4-understanding   Source File: MimeMessageHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Set the given text directly as content in non-multipart mode
 * or as default body part in multipart mode.
 * The "html" flag determines the content type to apply.
 * <p><b>NOTE:</b> Invoke {@link #addInline} <i>after</i> {@code setText};
 * else, mail readers might not be able to resolve inline references correctly.
 * @param text the text for the message
 * @param html whether to apply content type "text/html" for an
 * HTML mail, using default content type ("text/plain") else
 * @throws MessagingException in case of errors
 */
public void setText(String text, boolean html) throws MessagingException {
	Assert.notNull(text, "Text must not be null");
	MimePart partToUse;
	if (isMultipart()) {
		partToUse = getMainPart();
	}
	else {
		partToUse = this.mimeMessage;
	}
	if (html) {
		setHtmlTextToMimePart(partToUse, text);
	}
	else {
		setPlainTextToMimePart(partToUse, text);
	}
}
 
Example 3
@Test
void serviceShouldNotRemoveNonPrefixedHeaders() throws MessagingException {
    FakeMailetConfig mailetConfig = FakeMailetConfig.builder()
        .mailetName("Test")
        .setProperty("prefix", PREFIX)
        .build();
    mailet.init(mailetConfig);

    Mail mail = FakeMail.fromMessage(MimeMessageBuilder.mimeMessageBuilder()
        .addHeader(HEADER_NAME_PREFIX_1, "true")
        .addHeader(HEADER_NAME_NO_PREFIX, "true"));

    mailet.service(mail);

    assertThat(new MimeMessageUtils(mail.getMessage()).toHeaderList())
        .extracting("name")
        .contains(HEADER_NAME_NO_PREFIX)
        .doesNotContain(HEADER_NAME_PREFIX_1);
}
 
Example 4
Source Project: product-ei   Source File: GreenMailServer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Check inbox and make sure a particular email is deleted.
 *
 * @param emailSubject Email subject
 * @param protocol     protocol used to connect to the server
 * @return
 * @throws MessagingException if we're unable to connect to the store
 * @throws InterruptedException if thread sleep fails
 */
public static boolean checkEmailDeleted(String emailSubject, String protocol, GreenMailUser user)
        throws MessagingException, InterruptedException {
    boolean isEmailDeleted = false;
    long startTime = System.currentTimeMillis();

    while ((System.currentTimeMillis() - startTime) < WAIT_TIME_MS) {
        if (!isMailReceivedBySubject(emailSubject, EMAIL_INBOX, protocol, user)) {
            log.info("Email has been deleted successfully!");
            isEmailDeleted = true;
            break;
        }
        Thread.sleep(500);
    }
    return isEmailDeleted;
}
 
Example 5
Source Project: spring-boot-admin   Source File: MailNotifierTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void should_send_mail_using_custom_template_with_additional_properties()
		throws IOException, MessagingException {
	notifier.setTemplate("/de/codecentric/boot/admin/server/notify/custom-mail.html");
	notifier.getAdditionalProperties().put("customProperty", "HELLO WORLD!");

	StepVerifier
			.create(notifier.notify(
					new InstanceStatusChangedEvent(instance.getId(), instance.getVersion(), StatusInfo.ofDown())))
			.verifyComplete();

	ArgumentCaptor<MimeMessage> mailCaptor = ArgumentCaptor.forClass(MimeMessage.class);
	verify(sender).send(mailCaptor.capture());

	MimeMessage mail = mailCaptor.getValue();
	String body = extractBody(mail.getDataHandler());
	assertThat(body).isEqualTo(loadExpectedBody("expected-custom-mail"));
}
 
Example 6
/**
 * Sets flags for the message with the given UID. If {@code addUid} is set to {@code true}
 * {@link FolderListener} objects defined for this folder will be notified.
 * {@code silentListener} can be provided - this listener wouldn't be notified.
 * 
 * @param flags - new flags.
 * @param value - flags value.
 * @param uid - message UID.
 * @param silentListener - listener that shouldn't be notified.
 * @param addUid - defines whether or not listeners be notified.
 * @throws MessagingException 
 * @throws FolderException 
 */
@Override
protected void setFlagsInternal(
        Flags flags,
        boolean value,
        long uid,
        FolderListener silentListener,
        boolean addUid)
        throws MessagingException, FolderException 
{
    int msn = getMsn(uid);
    FileInfo fileInfo = searchMails().get(uid);
    imapService.setFlags(fileInfo, flags, value);
    
    Long uidNotification = null;
    if (addUid)
    {
        uidNotification = new Long(uid);
    }
    notifyFlagUpdate(msn, flags, uidNotification, silentListener);

}
 
Example 7
Source Project: james-project   Source File: URIRBLHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBlockedMultiPart() throws IOException, MessagingException {

    ArrayList<String> servers = new ArrayList<>();
    servers.add(URISERVER);

    SMTPSession session = setupMockedSMTPSession(setupMockedMail(setupMockedMimeMessageMP(
            "http://" + BAD_DOMAIN1 + "/" + " " + "http://" + GOOD_DOMAIN + "/")));

    URIRBLHandler handler = new URIRBLHandler();

    handler.setDNSService(setupMockedDnsServer());
    handler.setUriRblServer(servers);
    HookResult response = handler.onMessage(session, mockedMail);

    assertThat(HookReturnCode.deny()).describedAs("Email was rejected").isEqualTo(response.getResult());
}
 
Example 8
Source Project: james-project   Source File: SendMailHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Adds header to the message
 */
@Override
public HookResult onMessage(SMTPSession session, Mail mail) {
    LOGGER.debug("sending mail");

    try {
        queue.enQueue(mail);
        LOGGER.info("Successfully spooled mail {} from {} on {} for {}", mail.getName(), mail.getMaybeSender(), session.getRemoteAddress().getAddress(), mail.getRecipients());
    } catch (MessagingException me) {
        LOGGER.error("Unknown error occurred while processing DATA.", me);
        return HookResult.builder()
            .hookReturnCode(HookReturnCode.denySoft())
            .smtpDescription(DSNStatus.getStatus(DSNStatus.TRANSIENT, DSNStatus.UNDEFINED_STATUS) + " Error processing message.")
            .build();
    }
    return HookResult.builder()
        .hookReturnCode(HookReturnCode.ok())
        .smtpDescription(DSNStatus.getStatus(DSNStatus.SUCCESS, DSNStatus.CONTENT_OTHER) + " Message received")
        .build();
}
 
Example 9
Source Project: OpenAs2App   Source File: MimeUtil.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static MimeBodyPart readMimeBodyPart(InputStream source, InternetHeaders headers) throws IOException, MessagingException {
    // get the length of the Mime body's data
    int contentLength = getContentLength(headers);

    // read the data into a byte array
    DataInputStream dataIn = new DataInputStream(source);
    byte[] data = new byte[contentLength];
    dataIn.readFully(data);

    // convert the byte array to a MimeBodyPart
    String contentTransferEncoding = getHeader(headers, "Content-Transfer-Encoding");
    if (contentTransferEncoding == null) {
        contentTransferEncoding = Session.DEFAULT_CONTENT_TRANSFER_ENCODING;
    }
    return createMimeBodyPart(data, getHeader(headers, "Content-Type"), contentTransferEncoding);
}
 
Example 10
private void addBody(Part messagePart) throws MessagingException
{
    if (body != null)
    {
        attachmentList.add(new SubethaEmailMessagePart(messagePart, getPartFileName(getSubject() + " (part " + ++bodyNumber + ")", messagePart)));
        if (log.isInfoEnabled())
        {
            log.info(String.format("Attachment \"%s\" has been added.", attachmentList.get(attachmentList.size() - 1).getFileName()));
        }
    }
    else
    {
        body = new SubethaEmailMessagePart(messagePart, getPartFileName(getSubject(), messagePart));
        if (log.isDebugEnabled())
        {
            log.debug("Body has been added.");
        }
    }

}
 
Example 11
Source Project: james-project   Source File: MimeMessageWrapperTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test for JAMES-1154
 */
@Test
public void testMessageStreamWithUpatedContent() throws MessagingException, IOException {
    String newContent = "This is the new message content!";
    mw.setText(newContent);
    assertThat(mw.getContent()).isEqualTo(newContent);

    mw.saveChanges();

    BufferedReader reader = new BufferedReader(new InputStreamReader(mw.getMessageInputStream()));

    boolean contentUpdated = reader.lines()
        .anyMatch(line -> line.equals(newContent));
    reader.close();
    assertThat(contentUpdated).isTrue();
}
 
Example 12
Source Project: james-project   Source File: SetMimeHeaderHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void setMimeHeaderHandlerShouldReplaceSpecifiedHeader() throws MessagingException {

    MimeMessage mimeMessage = MimeMessageBuilder.mimeMessageBuilder()
        .addHeader(HEADER_NAME, "defaultHeaderValue")
        .setSubject("testmail")
        .setText("testtext")
        .addToRecipient("[email protected]")
        .addFrom("[email protected]")
        .build();
    MailImpl mail = MailImpl.builder()
        .name("ID=" + ThreadLocalRandom.current().nextLong())
        .mimeMessage(mimeMessage)
        .addRecipients("[email protected]", "[email protected]")
        .build();

    SetMimeHeaderHandler header = new SetMimeHeaderHandler();
    header.setHeaderName(HEADER_NAME);
    header.setHeaderValue(HEADER_VALUE);

    header.onMessage(fakeSMTPSession, mail);

    assertThat(mail.getMessage().getHeader(HEADER_NAME)).containsOnly(HEADER_VALUE);
}
 
Example 13
Source Project: james-project   Source File: BouncerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void bounceShouldCustomizeSocketExceptionByDefault() throws Exception {
    RemoteDeliveryConfiguration configuration = new RemoteDeliveryConfiguration(
        DEFAULT_REMOTE_DELIVERY_CONFIG,
        mock(DomainList.class));
    Bouncer testee = new Bouncer(configuration, mailetContext);

    Mail mail = FakeMail.builder().name("name").state(Mail.DEFAULT)
        .sender(MailAddressFixture.ANY_AT_JAMES)
        .build();
    String exceptionMessage = "Can not connect";
    testee.bounce(mail, new MessagingException("Exception message", new SocketException(exceptionMessage)));

    FakeMailContext.BouncedMail expected = new FakeMailContext.BouncedMail(FakeMailContext.fromMail(mail),
        "Hi. This is the James mail server at " + HELLO_NAME + ".\n" +
            "I'm afraid I wasn't able to deliver your message to the following addresses.\n" +
            "This is a permanent error; I've given up. Sorry it didn't work out. Below\n" +
            "I include the list of recipients and the reason why I was unable to deliver\n" +
            "your message.\n" +
            "\n" +
            "Socket exception: " + exceptionMessage + "\n\n",
        Optional.empty());
    assertThat(mailetContext.getSentMails()).isEmpty();
    assertThat(mailetContext.getBouncedMails()).containsOnly(expected);
}
 
Example 14
Source Project: java-technology-stack   Source File: JavaMailSenderTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testConnectionWithFailure() throws MessagingException {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost(null);

	thrown.expect(MessagingException.class);
	sender.testConnection();
}
 
Example 15
public Message sendMessage(Message message) throws AxelorException {
  try {
    if (message.getMediaTypeSelect() == MessageRepository.MEDIA_TYPE_MAIL) {
      return sendByMail(message);
    } else if (message.getMediaTypeSelect() == MessageRepository.MEDIA_TYPE_EMAIL) {
      return sendByEmail(message);
    } else if (message.getMediaTypeSelect() == MessageRepository.MEDIA_TYPE_CHAT) {
      return sendToUser(message);
    }
  } catch (MessagingException e) {
    TraceBackService.trace(e);
  }
  return message;
}
 
Example 16
Source Project: james-project   Source File: HasException.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static Class<? extends Throwable> castToThrowable(Class<?> cls) throws MessagingException {
    if (Throwable.class.isAssignableFrom(cls)) {
        return (Class<? extends Throwable>)cls;
    } else {
        throw new MessagingException("Specified class name is not a Throwable.");
    }
}
 
Example 17
/**
 * 获取消息附件中的文件.
 * @param part
 *            Part 对象
 * @param resourceList
 *            文件的集合(每个 ResourceFileBean 对象中存放文件名和 InputStream 对象)
 * @throws MessagingException
 *             the messaging exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
private void getRelatedPart(Part part, List<ResourceFileBean> resourceList) throws MessagingException, IOException {
	//验证 Part 对象的 MIME 类型是否与指定的类型匹配。
	if (part.isMimeType("multipart/related")) {
		Multipart mulContent = (Multipart) part.getContent();
		for (int j = 0, m = mulContent.getCount(); j < m; j++) {
			Part contentPart = mulContent.getBodyPart(j);
			if (!contentPart.isMimeType("text/*")) {
				String fileName = "Resource";
				//此方法返回 Part 对象的内容类型。
				String type = contentPart.getContentType();
				if (type != null) {
					type = type.substring(0, type.indexOf("/"));
				}
				fileName = fileName + "[" + type + "]";
				if (contentPart.getHeader("Content-Location") != null
						&& contentPart.getHeader("Content-Location").length > 0) {
					fileName = contentPart.getHeader("Content-Location")[0];
				}
				InputStream is = contentPart.getInputStream();
				resourceList.add(new ResourceFileBean(fileName, is));
			}
		}
	} else {
		Multipart mp = null;
		Object content = part.getContent();
		if (content instanceof Multipart) {
			mp = (Multipart) content;
		} else {
			return;
		}
		for (int i = 0, n = mp.getCount(); i < n; i++) {
			Part body = mp.getBodyPart(i);
			getRelatedPart(body, resourceList);
		}
	}
}
 
Example 18
Source Project: james-project   Source File: VacationReply.java    License: Apache License 2.0 5 votes vote down vote up
private Multipart generateNotificationContent() throws MessagingException {
    try {
        if (reason != null) {
            return generateNotificationContentFromReasonString();
        } else {
            return generateNotificationContentFromMime();
        }
    } catch (IOException e) {
        throw new MessagingException("Cannot read specified content", e);
    }
}
 
Example 19
Source Project: wandora   Source File: EmailModule.java    License: GNU General Public License v3.0 5 votes vote down vote up
public boolean send(List<String> recipients,String from,String subject,MimeMultipart content) {
        if(from==null) from=defaultFrom;
        if(subject==null) subject=defaultSubject;
        try{
//            Properties props=new Properties();
//            props.put("mail.smtp.host",smtpServer);
            Session session=Session.getDefaultInstance(mailProps,null);

            MimeMessage message=new MimeMessage(session);
            if(subject!=null) message.setSubject(subject);
            if(from!=null) message.setFrom(new InternetAddress(from));

            message.setContent(content);

            Transport transport = session.getTransport("smtp");
            if(smtpPort>0) transport.connect(smtpServer,smtpPort,smtpUser,smtpPass);
            else transport.connect(smtpServer,smtpUser,smtpPass);
            Address[] recipientAddresses=new Address[recipients.size()];
            for(int i=0;i<recipientAddresses.length;i++){
                recipientAddresses[i]=new InternetAddress(recipients.get(i));
            }
            transport.sendMessage(message,recipientAddresses);

            return true;
        }
        catch(MessagingException me){
            logging.warn("Couldn't send email",me);
            return false;
        }
    }
 
Example 20
private String getHeaderName(Message.RecipientType type)
        throws MessagingException {
    String headerName;

    if (type == Message.RecipientType.TO)
        headerName = "To";
    else if (type == Message.RecipientType.CC)
        headerName = "Cc";
    else if (type == Message.RecipientType.BCC)
        headerName = "Bcc";
    else
        throw new MessagingException("Invalid Recipient Type");
    return headerName;
}
 
Example 21
Source Project: elasticsearch-imap   Source File: MailFlowJob.java    License: Apache License 2.0 5 votes vote down vote up
public void execute() throws MessagingException, IOException {

        if (mailSource != null) {

            if (pattern == null) {
                mailSource.fetchAll(); // blocks
            } else {

                mailSource.fetch(pattern); // blocks

            }
        } else {
            throw new IllegalArgumentException("mailSource must not be null");
        }
    }
 
Example 22
/**
 * Import EML file as MailNode.
 */
public Mail importEml(String path, InputStream is) throws MessagingException, PathNotFoundException, ItemExistsException,
		VirusDetectedException, AccessDeniedException, RepositoryException, DatabaseException, UserQuotaExceededException,
		UnsupportedMimeTypeException, FileSizeExceededException, ExtensionException, AutomationException, IOException {
	log.debug("importEml({}, {})", path, is);
	Properties props = System.getProperties();
	props.put("mail.host", "smtp.dummydomain.com");
	props.put("mail.transport.protocol", "smtp");
	Mail newMail = null;

	try {
		// Convert file
		Session mailSession = Session.getDefaultInstance(props, null);
		MimeMessage msg = new MimeMessage(mailSession, is);
		Mail mail = MailUtils.messageToMail(msg);

		// Create phantom path. In this case we don't have the IMAP message
		// ID, son create a random one.
		mail.setPath(path + "/" + UUID.randomUUID().toString() + "-" + PathUtils.escape(mail.getSubject()));

		// Import files
		newMail = OKMMail.getInstance().create(null, mail);
		MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser());
	} catch (IOException e) {
		log.error("Error importing eml", e);
		throw e;
	} finally {
		IOUtils.closeQuietly(is);
	}

	log.debug("importEml: {}", newMail);
	return newMail;
}
 
Example 23
Source Project: FairEmail   Source File: MimeMessageEx.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void setFlag(Flags.Flag flag, boolean set) throws MessagingException {
    if (original == null)
        super.setFlag(flag, set);
    else
        original.setFlag(flag, set);
}
 
Example 24
Source Project: mail-importer   Source File: JavaxMailFolder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public int getUnreadMessageCount() throws RuntimeMessagingException {
  try {
    return delegate.getUnreadMessageCount();
  } catch (MessagingException e) {
    throw new RuntimeMessagingException(e);
  }
}
 
Example 25
Source Project: james-project   Source File: MessageProcessor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Computes the remoteReceivedHeaderInvalid.
 *
 * @return Boolean
 */
protected Boolean computeRemoteReceivedHeaderInvalid() throws MessagingException {
    Boolean isInvalid = Boolean.FALSE;
    try {
        getRemoteAddress();
    } catch (UnknownHostException e) {
        isInvalid = Boolean.TRUE;
    }
    return isInvalid;
}
 
Example 26
Source Project: james-project   Source File: AddSubjectPrefix.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void init() throws MessagingException {
    subjectPrefix = getInitParameter("subjectPrefix");

    if (Strings.isNullOrEmpty(subjectPrefix)) {
        throw new MessagingException("Please configure a valid subjectPrefix");
    }
}
 
Example 27
Source Project: james-project   Source File: HasExceptionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void matchShouldReturnEmptyWhenNonExceptionIsAttached() throws MessagingException {
    mockedMail.setAttribute(new Attribute(Mail.MAILET_ERROR, AttributeValue.of(new java.lang.String())));

    FakeMatcherConfig matcherConfig = FakeMatcherConfig.builder()
            .matcherName("HasException")
            .condition("java.lang.Exception")
            .build();

    testee.init(matcherConfig);

    assertThat(testee.match(mockedMail)).isEmpty();
}
 
Example 28
Source Project: blackduck-alert   Source File: MimeMultipartBuilder.java    License: Apache License 2.0 5 votes vote down vote up
public MimeMultipart build() throws MessagingException {
    final MimeMultipart email = new MimeMultipart("mixed");

    final MimeBodyPart emailBodyPart = buildEmailBodyPart();
    email.addBodyPart(emailBodyPart);
    addAttachmentBodyParts(email);

    return email;
}
 
Example 29
Source Project: mail-importer   Source File: JavaxMailMessage.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void writeTo(OutputStream os)
    throws IOException, RuntimeMessagingException {
  try {
    delegate.writeTo(os);
  } catch (MessagingException e) {
    throw new RuntimeMessagingException(e);
  }
}
 
Example 30
Source Project: spacewalk   Source File: SmtpMail.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public void setSubject(String subIn) {
    try {
        message.setSubject(subIn);
    }
    catch (MessagingException me) {
        String msg = "MessagingException while trying to send email: " +
                            me.toString();
        log.warn(msg);
        throw new JavaMailException(msg, me);
    }
}