javax.mail.MessagingException#getMessage ( )源码实例Demo

下面列出了javax.mail.MessagingException#getMessage ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: holdmail   文件: TestMailClient.java
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);
    }
}
 
源代码2 项目: spring-boot-examples   文件: EmailAction.java
@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();
    }
}
 
源代码3 项目: BotLibre   文件: Email.java
/**
 * 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) {}
	}
}
 
源代码4 项目: spring-boot-examples   文件: EmailAction.java
@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();
    }
}
 
源代码5 项目: spring-boot-examples   文件: EmailAction.java
@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();
    }
}
 
源代码6 项目: davmail   文件: HC4DavExchangeSession.java
@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());
    }
}
 
源代码7 项目: davmail   文件: DavExchangeSession.java
@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());
    }
}
 
源代码8 项目: nifi   文件: AbstractEmailProcessor.java
/**
 * 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);
            }
        }
    }
}
 
源代码9 项目: tomee   文件: EmailService.java
@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";
}
 
源代码10 项目: OpenAs2App   文件: BaseMessageMDN.java
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();
}
 
源代码11 项目: davmail   文件: EwsExchangeSession.java
@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);
}
 
/**
 * 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;
}
 
源代码13 项目: davmail   文件: HC4DavExchangeSession.java
/**
 * 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());
    }
}
 
源代码14 项目: davmail   文件: DavExchangeSession.java
/**
 * 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());
    }
}
 
/**
 * 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());
    }
}
 
源代码16 项目: holdmail   文件: OutgoingMailSender.java
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);
        }

    }
 
源代码17 项目: OpenAs2App   文件: BaseMessage.java
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>();
}
 
@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.)");
    }
}
 
源代码19 项目: BIMserver   文件: EmailMessage.java
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());
	}
}
 
源代码20 项目: eplmp   文件: NotifierBean.java
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);
}