Search in sources :

Example 46 with Message

use of javax.mail.Message in project Xponents by OpenSextant.

the class DefaultMailCrawl method collect.

/**
     * TODO:
     * 
     * pull all mail messages,
     * - create reasonable  FILE.msg  file name
     * - use XText to iterate over each msg file for conversion
     * - reimplement
     *
     * @throws IOException on failure to connect or collect.
     */
@Override
public void collect() throws IOException, ConfigException {
    File dateFolder = createDateFolder(new Date());
    if (dateFolder == null) {
        log.error("Unable to create directory: " + dateFolder);
        return;
    }
    Message[] messages = null;
    try {
        connect();
        messages = getMessages();
        if (messages == null) {
            log.info("No messages available - Exiting MailClient now");
            disconnect();
            return;
        }
    } catch (MessagingException javaMailErr) {
        throw new IOException("Unable to connect or get messages", javaMailErr);
    }
    int readCount = 0;
    int totalCount = 0;
    int available = messages.length;
    int errCount = 0;
    //
    for (Message message : messages) {
        ++totalCount;
        // Exit if too many errors.
        if (errCount > 10) {
            break;
        }
        try {
            if (config.doneReading(messages.length, readCount)) {
                // Done here.
                break;
            }
            /**
                 * Silently ignore deleted messages; items deleted while we were
                 * in session
                 */
            if (message.isExpunged()) {
                log.info("Message deleted during session; Unable to collect. Mail Subj: {}", message.getSubject());
                continue;
            }
            boolean newMessage = !message.isSet(Flags.Flag.SEEN);
            log.debug("Message Subject: " + message.getSubject() + "  new?: " + newMessage);
            boolean setForDeleteNow = false;
            String subject = message.getSubject();
            if (message.getSubject() == null) {
                log.info("Empty message title MSG number=" + message.getMessageNumber());
                //continue;
                subject = "No_Subject";
            }
            if ((!config.isReadNewMessagesOnly() || newMessage)) {
                // 1. Identify the email message.
                //    and determine if you need to capture it again.
                //
                String messageFilename = MessageConverter.createSafeFilename(subject);
                if (messageFilename.length() > 60) {
                    messageFilename = messageFilename.substring(0, 60);
                }
                String msgId = MessageConverter.getMessageID(message);
                if (msgId == null) {
                    log.error("How can a message ID be null? SUBJ={}", message.getSubject());
                    continue;
                }
                msgId = MessageConverter.getShorterMessageID(msgId);
                try {
                    if (listener != null && listener.exists(msgId)) {
                        //
                        continue;
                    }
                } catch (Exception err1) {
                    log.error("Collection error with mail.", err1);
                    continue;
                }
                readCount++;
                if (log.isDebugEnabled()) {
                    log.debug("Message: {}", message.getSubject());
                    String msg = String.format("Processing message: %s / %s of available: %s", readCount, totalCount, available);
                    log.debug(msg);
                }
                // Save file in archive, Convert it, etc.
                int status = saveMessageToFile(dateFolder, message, msgId, messageFilename);
                if (status < 0) {
                    ++errCount;
                }
                if (!config.isReadOnly() && config.isDeleteOnRead()) {
                    message.setFlag(Flags.Flag.DELETED, true);
                    String dbg = String.format("Processing message: %d / %d of available:%d", readCount, totalCount, available);
                    log.debug(dbg);
                    setForDeleteNow = true;
                }
            }
            //
            if (!newMessage && config.isDeleteOld() && !setForDeleteNow && !config.isReadOnly()) {
                message.setFlag(Flags.Flag.DELETED, true);
                log.debug("Deleting message: #{}", totalCount);
            }
        } catch (javax.mail.FolderClosedException connErr) {
            ++errCount;
        } catch (MessagingException me) {
            log.error("Failed to read messsage #{}", totalCount, me);
            ++errCount;
        } catch (IOException writeErr) {
            log.error("Failed to write msg.eml #{}", totalCount, writeErr);
            ++errCount;
        }
    }
    // Error on close is likely rare.
    try {
        disconnect();
    } catch (Exception javaMailErrOnClose) {
        log.error("Unkosher disconnect", javaMailErrOnClose);
    }
}
Also used : Message(javax.mail.Message) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException) File(java.io.File) Date(java.util.Date) ConfigException(org.opensextant.ConfigException) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException)

Example 47 with Message

use of javax.mail.Message in project midpoint by Evolveum.

the class PageSecurityQuestions method sendMailToUser.

public void sendMailToUser(final String userLogin, final String password, String newPassword, String host, String port, String sender, String receiver) {
    try {
        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.starttls.enable", "true");
        Session session = Session.getInstance(props, new javax.mail.Authenticator() {

            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userLogin, password);
            }
        });
        Message message = new MimeMessage(session);
        // TODO Localization
        message.setSubject("New Midpoint Password");
        message.setText("Password : " + newPassword + "\n");
        message.setFrom(new InternetAddress(sender));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver));
        Transport.send(message);
    /*
			 * Session mailSession = Session.getDefaultInstance(props);
			 * MimeMessage message = new MimeMessage(mailSession);
			 * 
			 * message.setSubject("Engerek KYS Yeni Şifreniz");
			 * 
			 * message.setText("User Login : " + userLogin + "\n Password : " +
			 * password + "\n"); message.setFrom(new InternetAddress(sender));
			 * message.addRecipient(Message.RecipientType.TO, new
			 * InternetAddress(receiver)); Transport transport =
			 * mailSession.getTransport(); transport.connect();
			 * transport.sendMessage(message,
			 * message.getRecipients(Message.RecipientType.TO));
			 * transport.close();
			 */
    } catch (MessagingException ex) {
        LoggingUtils.logUnexpectedException(LOGGER, "Mail send Exception", ex);
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) Properties(java.util.Properties) Session(javax.mail.Session) PasswordAuthentication(javax.mail.PasswordAuthentication)

Example 48 with Message

use of javax.mail.Message in project Axe by DongyuCai.

the class SimpleMailSender method sendHtmlMail.

/**
	 * 以HTML格式发送邮件
	 * 
	 * @param mailInfo
	 *            待发送的邮件信息
	 */
public static boolean sendHtmlMail(MailSenderInfo mailInfo) {
    // 判断是否需要身份认证
    MyAuthenticator authenticator = null;
    Properties pro = mailInfo.getProperties();
    // 如果需要身份认证,则创建一个密码验证器
    if (mailInfo.isValidate()) {
        authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
    }
    // 根据邮件会话属性和密码验证器构造一个发送邮件的session
    Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
    try {
        // 根据session创建一个邮件消息
        Message mailMessage = new MimeMessage(sendMailSession);
        // 创建邮件发送者地址
        Address from = new InternetAddress(mailInfo.getFromAddress());
        // 设置邮件消息的发送者
        mailMessage.setFrom(from);
        // 创建邮件的接收者地址,并设置到邮件消息中
        Address to = new InternetAddress(mailInfo.getToAddress());
        // Message.RecipientType.TO属性表示接收者的类型为TO
        mailMessage.setRecipient(Message.RecipientType.TO, to);
        // 设置邮件消息的主题
        mailMessage.setSubject(mailInfo.getSubject());
        // 设置邮件消息发送的时间
        mailMessage.setSentDate(new Date());
        // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
        Multipart mainPart = new MimeMultipart();
        // 创建一个包含HTML内容的MimeBodyPart
        BodyPart html = new MimeBodyPart();
        // 设置HTML内容
        html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
        mainPart.addBodyPart(html);
        // 将MiniMultipart对象设置为邮件内容
        mailMessage.setContent(mainPart);
        // 发送邮件
        Transport.send(mailMessage);
        return true;
    } catch (MessagingException ex) {
        ex.printStackTrace();
    }
    return false;
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) InternetAddress(javax.mail.internet.InternetAddress) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) Address(javax.mail.Address) InternetAddress(javax.mail.internet.InternetAddress) MessagingException(javax.mail.MessagingException) Properties(java.util.Properties) Date(java.util.Date) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart) Session(javax.mail.Session)

Example 49 with Message

use of javax.mail.Message in project opennms by OpenNMS.

the class JavaReadMailerTest method testGetText.

@Test
@Ignore
public void testGetText() throws JavaMailerException, MessagingException, IOException {
    JavaReadMailer rm = createGoogleReadMailer(getUser(), getPassword());
    List<Message> msgs = rm.retrieveMessages();
    for (Message msg : msgs) {
        JavaReadMailer.getText(msg);
        JavaReadMailer.string2Lines("abc\nxyz");
    }
}
Also used : Message(javax.mail.Message) SendmailMessage(org.opennms.netmgt.config.javamail.SendmailMessage) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 50 with Message

use of javax.mail.Message in project selenium-tests by Wikia.

the class EmailUtils method deleteAllEmails.

public static void deleteAllEmails(String userName, String password) {
    try {
        // establishing connections
        Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", "imaps");
        Session session = Session.getDefaultInstance(props, null);
        session.setDebug(false);
        Store store = session.getStore("imaps");
        store.connect("imap.googlemail.com", userName, password);
        // getInbox
        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_WRITE);
        Message[] messages = inbox.getMessages();
        if (messages.length != 0) {
            for (int i = 0; i < messages.length; i++) {
                messages[i].setFlag(Flags.Flag.DELETED, true);
            }
        } else {
            PageObjectLogging.log("Mail", "There are no messages in inbox", true);
        }
        store.close();
    } catch (NoSuchProviderException e) {
        PageObjectLogging.log("Mail", e, false);
    } catch (MessagingException e) {
        PageObjectLogging.log("Mail", e, false);
    }
}
Also used : Message(javax.mail.Message) MessagingException(javax.mail.MessagingException) Store(javax.mail.Store) Properties(java.util.Properties) Folder(javax.mail.Folder) NoSuchProviderException(javax.mail.NoSuchProviderException) Session(javax.mail.Session)

Aggregations

Message (javax.mail.Message)149 MimeMessage (javax.mail.internet.MimeMessage)81 MessagingException (javax.mail.MessagingException)53 InternetAddress (javax.mail.internet.InternetAddress)48 Folder (javax.mail.Folder)41 Test (org.junit.Test)40 Session (javax.mail.Session)37 Properties (java.util.Properties)36 Store (javax.mail.Store)28 Date (java.util.Date)19 MockEndpoint (org.apache.camel.component.mock.MockEndpoint)19 MimeMultipart (javax.mail.internet.MimeMultipart)18 Mailbox (org.jvnet.mock_javamail.Mailbox)18 MimeBodyPart (javax.mail.internet.MimeBodyPart)16 PasswordAuthentication (javax.mail.PasswordAuthentication)15 IOException (java.io.IOException)13 ArrayList (java.util.ArrayList)13 Multipart (javax.mail.Multipart)13 Address (javax.mail.Address)11 HashMap (java.util.HashMap)8