Java Code Examples for javax.mail.MessagingException#getMessage()

The following examples show how to use javax.mail.MessagingException#getMessage() . 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: TestMailClient.java    From holdmail with Apache License 2.0 7 votes vote down vote up
public void sendEmail(String fromEmail, String toEmail, String subject, String textBody, String htmlBody) {
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromEmail));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
        message.setSubject(subject);

        // Set the message
        createMultiMimePart(message, textBody, htmlBody);

        Transport.send(message);
    }
    catch (MessagingException e) {
        throw new HoldMailException("Failed to send email : " + e.getMessage(), e);
    }
}
 
Example 2
Source File: EmailAction.java    From spring-boot-examples with Apache License 2.0 6 votes vote down vote up
@PostMapping(value = "html")
public String sendHtmlMsg(String msg, String email) {
    if (StringUtils.isEmpty(msg) || StringUtils.isEmpty(email)) {
        return "请输入要发送消息和目标邮箱";
    }
    try {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
        messageHelper.setFrom(sendName);
        messageHelper.setTo(email);
        messageHelper.setSubject("HTML邮件");
        String html = "<div><h1><a name=\"hello\"></a><span>Hello</span></h1><blockquote><p><span>this is a html email.</span></p></blockquote><p>&nbsp;</p><p><span>"
                + msg + "</span></p></div>";
        messageHelper.setText(html, true);
        mailSender.send(message);
        return "发送成功";
    } catch (MessagingException e) {
        e.printStackTrace();
        return "发送失败:" + e.getMessage();
    }
}
 
Example 3
Source File: AbstractEmailProcessor.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Fills the internal message queue if such queue is empty. This is due to
 * the fact that per single session there may be multiple messages retrieved
 * from the email server (see FETCH_SIZE).
 */
private synchronized void fillMessageQueueIfNecessary() {
    if (this.messageQueue.isEmpty()) {
        Object[] messages;
        try {
            messages = this.messageReceiver.receive();
        } catch (MessagingException e) {
            String errorMsg = "Failed to receive messages from Email server: [" + e.getClass().getName()
                    + " - " + e.getMessage();
            this.getLogger().error(errorMsg);
            throw new ProcessException(errorMsg, e);
        }

        if (messages != null) {
            for (Object message : messages) {
                Assert.isTrue(message instanceof Message, "Message is not an instance of javax.mail.Message");
                this.messageQueue.offer((Message) message);
            }
        }
    }
}
 
Example 4
Source File: DavExchangeSession.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void sendMessage(MimeMessage mimeMessage) throws IOException {
    try {
        // need to create draft first
        String itemName = UUID.randomUUID().toString() + ".EML";
        HashMap<String, String> properties = new HashMap<>();
        properties.put("draft", "9");
        String contentType = mimeMessage.getContentType();
        if (contentType != null && contentType.startsWith("text/plain")) {
            properties.put("messageFormat", "1");
        } else {
            properties.put("mailOverrideFormat", String.valueOf(ENCODING_PREFERENCE | ENCODING_MIME | BODY_ENCODING_TEXT_AND_HTML));
            properties.put("messageFormat", "2");
        }
        createMessage(DRAFTS, itemName, properties, mimeMessage);
        MoveMethod method = new MoveMethod(URIUtil.encodePath(getFolderPath(DRAFTS + '/' + itemName)),
                URIUtil.encodePath(getFolderPath(SENDMSG)), false);
        // set header if saveInSent is disabled 
        if (!Settings.getBooleanProperty("davmail.smtpSaveInSent", true)) {
            method.setRequestHeader("Saveinsent", "f");
        }
        moveItem(method);
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    }
}
 
Example 5
Source File: HC4DavExchangeSession.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void sendMessage(MimeMessage mimeMessage) throws IOException {
    try {
        // need to create draft first
        String itemName = UUID.randomUUID().toString() + ".EML";
        HashMap<String, String> properties = new HashMap<>();
        properties.put("draft", "9");
        String contentType = mimeMessage.getContentType();
        if (contentType != null && contentType.startsWith("text/plain")) {
            properties.put("messageFormat", "1");
        } else {
            properties.put("mailOverrideFormat", String.valueOf(ENCODING_PREFERENCE | ENCODING_MIME | BODY_ENCODING_TEXT_AND_HTML));
            properties.put("messageFormat", "2");
        }
        createMessage(DRAFTS, itemName, properties, mimeMessage);
        HttpMove httpMove = new HttpMove(URIUtil.encodePath(getFolderPath(DRAFTS + '/' + itemName)),
                URIUtil.encodePath(getFolderPath(SENDMSG)), false);
        // set header if saveInSent is disabled
        if (!Settings.getBooleanProperty("davmail.smtpSaveInSent", true)) {
            httpMove.setHeader("Saveinsent", "f");
        }
        moveItem(httpMove);
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    }
}
 
Example 6
Source File: EmailAction.java    From spring-boot-examples with Apache License 2.0 6 votes vote down vote up
@PostMapping(value = "html_with_template")
public String sendHtmlByTemplate(String msg, String email) {
    if (StringUtils.isEmpty(msg) || StringUtils.isEmpty(email)) {
        return "请输入要发送消息和目标邮箱";
    }

    try {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
        messageHelper.setFrom(sendName);
        messageHelper.setTo(email);
        messageHelper.setSubject("使用HTML模板文件发送邮件");

        Context context = new Context();
        context.setVariable("msg", msg);
        messageHelper.setText(templateEngine.process("EmailTemplate", context), true);
        mailSender.send(message);
        return "发送成功";
    } catch (MessagingException e) {
        e.printStackTrace();
        return "发送失败:" + e.getMessage();
    }
}
 
Example 7
Source File: EmailAction.java    From spring-boot-examples with Apache License 2.0 6 votes vote down vote up
@PostMapping(value = "html_with_img")
public String sendHtmlWithImg(String msg, String email) {
    if (StringUtils.isEmpty(msg) || StringUtils.isEmpty(email)) {
        return "请输入要发送消息和目标邮箱";
    }
    try {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
        messageHelper.setFrom(sendName);
        messageHelper.setTo(email);
        messageHelper.setSubject("带静态资源图片的HTML邮件");
        String html = "<div><h1><a name=\"hello\"></a><span>Hello</span></h1><blockquote><p><span>this is a html email.</span></p></blockquote><p>&nbsp;</p><p><span>"
                + msg + "</span></p><img src='cid:myImg' /></div>";
        messageHelper.setText(html, true);
        File file = new File("src/main/resources/wei.jpg");
        messageHelper.addInline("myImg", file);
        mailSender.send(message);
        return "发送成功";
    } catch (MessagingException e) {
        e.printStackTrace();
        return "发送失败:" + e.getMessage();
    }
}
 
Example 8
Source File: Email.java    From BotLibre with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Connect and verify the email settings.
 */
public void connect() {
	Store store = null;
	try {
		log("Connecting email.", Level.FINER);
		store = connectStore();
		connectSession();
		log("Done connecting email.", Level.FINER);
	} catch (MessagingException messagingException) {
		BotException exception = new BotException("Failed to connect - " + messagingException.getMessage(), messagingException);
		log(exception);
		throw exception;
	} finally {
		try {
			if (store != null) {
				store.close();
			}
		} catch (Exception ignore) {}
	}
}
 
Example 9
Source File: BaseMessageMDN.java    From OpenAs2App with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void writeObject(java.io.ObjectOutputStream out) throws IOException {
    // write partnership info
    out.writeObject(partnership);

    // write attributes
    out.writeObject(attributes);

    // write text
    out.writeObject(text);

    // write message headers
    Enumeration<String> en = headers.getAllHeaderLines();

    while (en.hasMoreElements()) {
        out.writeBytes(en.nextElement() + "\r\n");
    }

    out.writeBytes("\r\n");

    // write the mime body
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {
        if (data != null) {
            baos.write(1);
            data.writeTo(baos);
        } else {
            baos.write(0);
        }
    } catch (MessagingException e) {
        throw new IOException("Messaging exception: " + e.getMessage());
    }

    out.write(baos.toByteArray());
    baos.close();
}
 
Example 10
Source File: EwsExchangeSession.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void createMessage(String folderPath, String messageName, HashMap<String, String> properties, MimeMessage mimeMessage) throws IOException {
    EWSMethod.Item item = new EWSMethod.Item();
    item.type = "Message";
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        mimeMessage.writeTo(baos);
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    }
    baos.close();
    item.mimeContent = IOUtil.encodeBase64(baos.toByteArray());

    List<FieldUpdate> fieldUpdates = buildProperties(properties);
    if (!properties.containsKey("draft")) {
        // need to force draft flag to false
        if (properties.containsKey("read")) {
            fieldUpdates.add(Field.createFieldUpdate("messageFlags", "1"));
        } else {
            fieldUpdates.add(Field.createFieldUpdate("messageFlags", "0"));
        }
    }
    fieldUpdates.add(Field.createFieldUpdate("urlcompname", messageName));
    item.setFieldUpdates(fieldUpdates);
    CreateItemMethod createItemMethod = new CreateItemMethod(MessageDisposition.SaveOnly, getFolderId(folderPath), item);
    executeMethod(createItemMethod);
}
 
Example 11
Source File: ExceptionHandlingMailSendingTemplate.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * handles the sendFailedException
 * <p>
 * creates a MessageSendStatus which contains a translateable info or error message, and the knowledge if the user can proceed with its action. 
 * 
 * @param e
 * @throws OLATRuntimeException return MessageSendStatus
 */
private MessageSendStatus handleSendFailedException(final SendFailedException e) {
	// get wrapped excpetion
	MessageSendStatus messageSendStatus = null;
	
	final MessagingException me = (MessagingException) e.getNextException();
	if (me instanceof AuthenticationFailedException) {
		messageSendStatus = createAuthenticationFailedMessageSendStatus();
		return messageSendStatus;
	}
	
	final String message = me.getMessage();
	if (message.startsWith("553")) {
		messageSendStatus = createInvalidDomainMessageSendStatus();
	} else if (message.startsWith("Invalid Addresses")) {
		messageSendStatus = createInvalidAddressesMessageSendStatus(e.getInvalidAddresses());
	} else if (message.startsWith("503 5.0.0")) {
		messageSendStatus = createNoRecipientMessageSendStatus();
	} else if (message.startsWith("Unknown SMTP host")) {
		messageSendStatus = createUnknownSMTPHost();
	} else if (message.startsWith("Could not connect to SMTP host")) {
		messageSendStatus = createCouldNotConnectToSmtpHostMessageSendStatus();
	} else {
		List<ContactList> emailToContactLists = getTheToContactLists();
		String exceptionMessage = "";
		for (ContactList contactList : emailToContactLists) {
			exceptionMessage += contactList.toString();
		}
		throw new OLATRuntimeException(ContactUIModel.class, exceptionMessage, me);
	}
	return messageSendStatus;
}
 
Example 12
Source File: HC4DavExchangeSession.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Send message.
 *
 * @param messageBody MIME message body
 * @throws IOException on error
 */
public void sendMessage(byte[] messageBody) throws IOException {
    try {
        sendMessage(new MimeMessage(null, new SharedByteArrayInputStream(messageBody)));
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    }
}
 
Example 13
Source File: DavExchangeSession.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Send message.
 *
 * @param messageBody MIME message body
 * @throws IOException on error
 */
public void sendMessage(byte[] messageBody) throws IOException {
    try {
        sendMessage(new MimeMessage(null, new SharedByteArrayInputStream(messageBody)));
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    }
}
 
Example 14
Source File: SubethaEmailMessagePart.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Object can be built on existing message part only.
 * 
 * @param messagePart Message part.
 */
public SubethaEmailMessagePart(Part messagePart)
{
    ParameterCheck.mandatory("messagePart", messagePart);

    try
    {
        fileSize = messagePart.getSize();
        fileName = messagePart.getFileName();
        contentType = messagePart.getContentType();

        Matcher matcher = encodingExtractor.matcher(contentType);
        if (matcher.find())
        {
            encoding = matcher.group(1);
            if (!Charset.isSupported(encoding))
            {
                throw new EmailMessageException(ERR_UNSUPPORTED_ENCODING, encoding);
            }
        }

        try
        {
            contentInputStream = messagePart.getInputStream(); 
        }
        catch (Exception ex)
        {
            throw new EmailMessageException(ERR_FAILED_TO_READ_CONTENT_STREAM, ex.getMessage());
        }
    }
    catch (MessagingException e)
    {
        throw new EmailMessageException(ERR_INCORRECT_MESSAGE_PART, e.getMessage());
    }
}
 
Example 15
Source File: OutgoingMailSender.java    From holdmail with Apache License 2.0 5 votes vote down vote up
public void redirectMessage(String recipient, String rawBody) {

        // TODO: this is a crude first pass at bouncing a mail and probably needs to be a little more sophisticated

        try {

            Session session = getMailSession();
            Message message = initializeMimeMessage(rawBody, session);

            // wipe out ALL exisitng recipients
            message.setRecipients(Message.RecipientType.TO, new Address[]{});
            message.setRecipients(Message.RecipientType.CC, new Address[]{});
            message.setRecipients(Message.RecipientType.BCC, new Address[]{});

            // and set the new recipient
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));

            InternetAddress[] parsedFrom = InternetAddress.parse(getSenderFrom());
            if(parsedFrom.length > 0) {
                message.setFrom(parsedFrom[0]);
                logger.info("Outgoing mail will have From: " + parsedFrom[0].getAddress());
            }

            sendMessage(message);

            logger.info("Outgoing mail forwarded to " + recipient);

        } catch (MessagingException e) {
            throw new HoldMailException("couldn't send mail: " + e.getMessage(), e);
        }

    }
 
Example 16
Source File: EmailService.java    From tomee with Apache License 2.0 5 votes vote down vote up
@POST
public String lowerCase(final String message) {

    try {

        //Create some properties and get the default Session
        final Properties props = new Properties();
        props.put("mail.smtp.host", "your.mailserver.host");
        props.put("mail.debug", "true");

        final Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("MyUsername", "MyPassword");
            }
        });

        //Set this just to see some internal logging
        session.setDebug(true);

        //Create a message
        final MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("[email protected]"));
        final InternetAddress[] address = {new InternetAddress("[email protected]")};
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject("JavaMail API test");
        msg.setSentDate(new Date());
        msg.setText(message, "UTF-8");


        Transport.send(msg);
    } catch (final MessagingException e) {
        return "Failed to send message: " + e.getMessage();
    }

    return "Sent";
}
 
Example 17
Source File: BaseMessage.java    From OpenAs2App with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
    // read in partnership
    partnership = (Partnership) in.readObject();

    // read in attributes
    attributes = (Map<String, String>) in.readObject();

    // read in data history
    history = (DataHistory) in.readObject();

    try {
        // read in message headers
        headers = new InternetHeaders(in);

        // read in mime body 
        if (in.read() == 1) {
            data = new MimeBodyPart(in);
        }
    } catch (MessagingException me) {
        throw new IOException("Messaging exception: " + me.getMessage());
    }

    // read in MDN
    MDN = (MessageMDN) in.readObject();

    if (MDN != null) {
        MDN.setMessage(this);
    }

    customOuterMimeHeaders = new HashMap<String, String>();
}
 
Example 18
Source File: HasMailAttributeWithValueRegexTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
void testHeaderIsNotMatchedCauseValue() throws MessagingException {

    String invalidRegex = "(!(";
    String regexException = null;
    String exception = "Malformed pattern: " + invalidRegex;

    setRegex(invalidRegex);
    setupMockedMail();

    try {
        setupMatcher();
    } catch (MessagingException m) {
        regexException = m.getMessage();
    }

    Collection<MailAddress> matchedRecipients = matcher.match(mockedMail);

    assertNull(matchedRecipients);
    
    try {
        assertThat(regexException).isEqualTo(exception);
    } catch (AssertionFailedError e) {
        // NOTE the expected exception changes when the project is built/run
        // against non java 1.4 jvm. 
        assertThat(regexException).isEqualTo(exception + " (org.apache.oro.text.regex.MalformedPatternException: Unmatched parentheses.)");
    }
}
 
Example 19
Source File: EmailMessage.java    From BIMserver with GNU Affero General Public License v3.0 4 votes vote down vote up
public void send() throws MessagingException, UserException {
	Properties props = new Properties();
	ServerSettings serverSettings = bimServer.getServerSettingsCache().getServerSettings();
	props.put("mail.smtp.localhost", "bimserver.org");
	String smtpProps = serverSettings.getSmtpProtocol() == SmtpProtocol.SMTPS ? "mail.smtps.port" : "mail.smtp.port";
	
	props.put("mail.smtp.connectiontimeout", 10000);
	props.put("mail.smtp.timeout", 10000);
	props.put("mail.smtp.writetimeout", 10000);
	props.put("mail.smtp.host", serverSettings.getSmtpServer());
	props.put("mail.smtp.port", serverSettings.getSmtpPort());
	props.put("mail.smtp.auth", serverSettings.getSmtpUsername() != null);
	
	props.put(smtpProps, serverSettings.getSmtpPort());
	
	if (serverSettings.getSmtpProtocol() == SmtpProtocol.STARTTLS) {
		props.put("mail.smtp.starttls.enable","true");
	}

	Session session = null;
	
	if (serverSettings.getSmtpUsername() != null) {
		session = Session.getInstance(props, new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(serverSettings.getSmtpUsername(), serverSettings.getSmtpPassword());
			}
		});
	} else {
		session = Session.getInstance(props);
	}
	
	try {
		Message message = new MimeMessage(session);
		message.setSubject(subject);
		message.setRecipients(to, addressTo);
		message.setContent(body, contentType);
		message.setFrom(from);
		
		Transport.send(message, addressTo);
	} catch (MessagingException e) {
		LOGGER.error("Error sending email " + body + " " + e.getMessage());
		throw new UserException("Error sending email " + e.getMessage());
	}
}
 
Example 20
Source File: NotifierBean.java    From eplmp with Eclipse Public License 1.0 4 votes vote down vote up
private void logMessagingException(MessagingException pMEx) {
    String logMessage = "Message format error. \n\tMail can't be sent. \n\t" + pMEx.getMessage();
    LOGGER.log(Level.SEVERE, logMessage, pMEx);
}