javax.mail.MessagingException Java Examples

The following examples show how to use javax.mail.MessagingException. 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: MimeMessageHelper.java    From spring4-understanding with 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 #2
Source File: SetMimeHeaderHandlerTest.java    From james-project with 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 #3
Source File: BouncerTest.java    From james-project with 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 #4
Source File: MimePackage.java    From ats-framework with 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 #5
Source File: RemoveMimeHeaderByPrefixTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: GreenMailServer.java    From product-ei with 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 #7
Source File: MailNotifierTest.java    From spring-boot-admin with 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 #8
Source File: AlfrescoImapFolder.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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 #9
Source File: MimeMessageWrapperTest.java    From james-project with 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 #10
Source File: SubethaEmailMessage.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 File: URIRBLHandlerTest.java    From james-project with 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 #12
Source File: MimeUtil.java    From OpenAs2App with 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 #13
Source File: SendMailHandler.java    From james-project with 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 #14
Source File: BasicEmailService.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
protected void updateHeaders() throws MessagingException
{
	super.updateHeaders();
	if (m_id != null)
	{
		setHeader("Message-Id", m_id);
	}
}
 
Example #15
Source File: ArdulinkMailMessageCountListener.java    From Ardulink-1 with Apache License 2.0 5 votes vote down vote up
public void messagesAdded(MessageCountEvent ev) {
    Message[] msgs = ev.getMessages();
	logger.info("Got {} new messages", msgs.length);

    for (int i = 0; i < msgs.length; i++) {
		try {
			manageMessage(msgs[i]);
		} catch (IOException ioex) { 
		    ioex.printStackTrace();	
		} catch (MessagingException mex) {
		    mex.printStackTrace();
		}
    }
}
 
Example #16
Source File: ToSenderFolder.java    From james-project with Apache License 2.0 5 votes vote down vote up
private void doService(Mail mail) throws MessagingException {
    if (mail.hasSender()) {
        MailAddress sender = mail.getMaybeSender().get();
        Username username = retrieveUser(sender);

        mailboxAppender.append(mail.getMessage(), username, folder);

        LOGGER.error("Local delivery with ToSenderFolder mailet for mail {} with sender {} in folder {}", mail.getName(), sender, folder);
    }
}
 
Example #17
Source File: MimeMessageHelper.java    From java-technology-stack with MIT License 5 votes vote down vote up
public void setCc(String[] cc) throws MessagingException {
	Assert.notNull(cc, "Cc address array must not be null");
	InternetAddress[] addresses = new InternetAddress[cc.length];
	for (int i = 0; i < cc.length; i++) {
		addresses[i] = parseAddress(cc[i]);
	}
	setCc(addresses);
}
 
Example #18
Source File: MimeMessageHelper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void setPlainTextToMimePart(MimePart mimePart, String text) throws MessagingException {
	if (getEncoding() != null) {
		mimePart.setText(text, getEncoding());
	}
	else {
		mimePart.setText(text);
	}
}
 
Example #19
Source File: AbstractPriorityMatcher.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<MailAddress> match(Mail mail) throws MessagingException {
    return AttributeUtils.getValueAndCastFromMail(mail, MailPrioritySupport.MAIL_PRIORITY, Integer.class)
            .filter(this::priorityMatch)
            .map(any -> mail.getRecipients())
            .orElse(ImmutableList.of());
}
 
Example #20
Source File: SMIMESign.java    From james-project with Apache License 2.0 5 votes vote down vote up
/**
 * If the <CODE>&lt;rebuildFrom&gt;</CODE> init parameter is missing sets it to <I>true</I>.
 */
@Override
protected void initRebuildFrom() throws MessagingException {
    setRebuildFrom((getInitParameter("rebuildFrom") == null) ? true : Boolean.parseBoolean(getInitParameter("rebuildFrom")));
    if (isDebug()) {
        if (isRebuildFrom()) {
            LOGGER.debug("Will modify the \"From:\" header.");
        } else {
            LOGGER.debug("Will leave the \"From:\" header unchanged.");
        }
    }
}
 
Example #21
Source File: ImapConnection.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
public Enumeration getMatchingHeaderLines(String[] requestedHeaders) throws IOException, MessagingException, InterruptedException {
    Enumeration result = message.getMatchingHeaderLinesFromHeaders(requestedHeaders);
    if (result == null) {
        loadMessage();
        result = message.getMatchingHeaderLines(requestedHeaders);
    }
    return result;
}
 
Example #22
Source File: EmailAccount.java    From teammates with GNU General Public License v2.0 5 votes vote down vote up
private String getTextFromPart(Part part) throws MessagingException, IOException {
    if (part.isMimeType("multipart/alternative")) {
        return getTextFromMultiPartAlternative((Multipart) part.getContent());
    } else if (part.isMimeType("multipart/digest")) {
        return getTextFromMultiPartDigest((Multipart) part.getContent());
    } else if (mimeTypeCanBeHandledAsMultiPartMixed(part)) {
        return getTextHandledAsMultiPartMixed(part);
    }

    return null;
}
 
Example #23
Source File: OKMMail.java    From document-management-system with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Import MSG file as MailNode.
 */
public Mail importMsg(String path, InputStream is) throws MessagingException, PathNotFoundException, ItemExistsException,
		VirusDetectedException, AccessDeniedException, RepositoryException, DatabaseException, UserQuotaExceededException,
		UnsupportedMimeTypeException, FileSizeExceededException, ExtensionException, AutomationException, IOException {
	log.debug("importMsg({}, {})", path, is);
	Mail newMail = null;

	try {
		// Convert file
		MsgParser msgp = new MsgParser();
		Message msg = msgp.parseMsg(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 msg", e);
		throw e;
	} finally {
		IOUtils.closeQuietly(is);
	}

	log.debug("importMsg: {}", newMail);
	return newMail;
}
 
Example #24
Source File: MimeDecodingMailetTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
void serviceShouldNotThrowWhenAttributeContentIsNotAMap() throws MessagingException {
    FakeMailetConfig mailetConfig = FakeMailetConfig.builder()
            .mailetName("Test")
            .mailetContext(mailetContext)
            .setProperty(MimeDecodingMailet.ATTRIBUTE_PARAMETER_NAME, MAIL_ATTRIBUTE.asString())
            .build();
    testee.init(mailetConfig);

    FakeMail mail = FakeMail.defaultFakeMail();
    mail.setAttribute(new Attribute(MAIL_ATTRIBUTE, AttributeValue.of(ImmutableList.of())));

    testee.service(mail);
}
 
Example #25
Source File: FakeMailTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void getMaybeSenderShouldHandleNoSender() throws MessagingException {
    assertThat(
        FakeMail.builder()
            .name("mail")
            .build()
            .getMaybeSender())
        .isEqualTo(MaybeSender.nullSender());
}
 
Example #26
Source File: ToRepository.java    From james-project with Apache License 2.0 5 votes vote down vote up
private MailRepository selectRepository() throws MessagingException {
    try {
        return mailStore.select(repositoryPath);
    } catch (Exception e) {
        throw new MessagingException("Failed to retrieve MailRepository for url " + repositoryPath, e);
    }
}
 
Example #27
Source File: MailUtil.java    From jeecg with Apache License 2.0 5 votes vote down vote up
/**
 * 发送电子邮件
 * 
 * @param smtpHost
 *            发信主机
 * @param receiver
 *            邮件接收者
 * @param title
 *            邮件的标题
 * @param content
 *            邮件的内容
 * @param sender
 *            邮件发送者
 * @param user
 *            发送者邮箱用户名
 * @param pwd
 *            发送者邮箱密码
 * @throws MessagingException 
 */
public static void sendEmail(String smtpHost, String receiver,
		String title, String content, String sender, String user, String pwd) throws MessagingException
		 {
	Properties props = new Properties();
	props.put("mail.host", smtpHost);
	props.put("mail.transport.protocol", "smtp");
	// props.put("mail.smtp.host",smtpHost);//发信的主机,这里要把您的域名的SMTP指向正确的邮件服务器上,这里一般不要动!
	props.put("mail.smtp.auth", "true");
	Session s = Session.getDefaultInstance(props);
	s.setDebug(true);
	MimeMessage message = new MimeMessage(s);
	// 给消息对象设置发件人/收件人/主题/发信时间
	// 发件人的邮箱
	InternetAddress from = new InternetAddress(sender);
	message.setFrom(from);
	InternetAddress to = new InternetAddress(receiver);
	message.setRecipient(Message.RecipientType.TO, to);
	message.setSubject(title);
	message.setSentDate(new Date());
	// 给消息对象设置内容
	BodyPart mdp = new MimeBodyPart();// 新建一个存放信件内容的BodyPart对象
	mdp.setContent(content, "text/html;charset=gb2312");// 给BodyPart对象设置内容和格式/编码方式防止邮件出现乱码
	Multipart mm = new MimeMultipart();// 新建一个MimeMultipart对象用来存放BodyPart对
	// 象(事实上可以存放多个)
	mm.addBodyPart(mdp);// 将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
	message.setContent(mm);// 把mm作为消息对象的内容

	message.saveChanges();
	Transport transport = s.getTransport("smtp");
	transport.connect(smtpHost, user, pwd);// 设置发邮件的网关,发信的帐户和密码,这里修改为您自己用的
	transport.sendMessage(message, message.getAllRecipients());
	transport.close();
}
 
Example #28
Source File: IncomingImapMessage.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void buildMessageInternal() throws MessagingException
{
    setMessageHeaders();
    // Add Imap Content Aspect with properties
    NodeService nodeService = serviceRegistry.getNodeService();
    nodeService.addAspect(this.messageFileInfo.getNodeRef(), ImapModel.ASPECT_IMAP_CONTENT, null);
    imapService.setFlags(messageFileInfo, flags, true);
    // Write content
    writeContent();
}
 
Example #29
Source File: Core.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
private static void onHeaders(Context context, JSONArray jargs, EntityFolder folder, EntityMessage message, IMAPFolder ifolder) throws MessagingException {
    // Download headers
    DB db = DB.getInstance(context);

    if (message.headers != null)
        return;

    IMAPMessage imessage = (IMAPMessage) ifolder.getMessageByUID(message.uid);
    if (imessage == null)
        throw new MessageRemovedException();

    MessageHelper helper = new MessageHelper(imessage, context);
    db.message().setMessageHeaders(message.id, helper.getHeaders());
}
 
Example #30
Source File: JavaMailSenderTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void javaMailSenderWithCustomSession() throws MessagingException {
	final Session session = Session.getInstance(new Properties());
	MockJavaMailSender sender = new MockJavaMailSender() {
		@Override
		protected Transport getTransport(Session sess) throws NoSuchProviderException {
			assertEquals(session, sess);
			return super.getTransport(sess);
		}
	};
	sender.setSession(session);
	sender.setHost("host");
	sender.setUsername("username");
	sender.setPassword("password");

	MimeMessage mimeMessage = sender.createMimeMessage();
	mimeMessage.setSubject("custom");
	mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	mimeMessage.setSentDate(new GregorianCalendar(2005, 3, 1).getTime());
	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));
}