Example usage for javax.mail.internet MimeMessage MimeMessage

List of usage examples for javax.mail.internet MimeMessage MimeMessage

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage MimeMessage.

Prototype

public MimeMessage(MimeMessage source) throws MessagingException 

Source Link

Document

Constructs a new MimeMessage with content initialized from the source MimeMessage.

Usage

From source file:fr.xebia.cloud.cloudinit.CloudInitUserDataBuilder.java

private CloudInitUserDataBuilder(@Nonnull Charset charset) {
    super();//from w w w  .  ja  v a 2s  . c  om
    userDataMimeMessage = new MimeMessage(Session.getDefaultInstance(new Properties()));
    userDataMultipart = new MimeMultipart();
    try {
        userDataMimeMessage.setContent(userDataMultipart);
    } catch (MessagingException e) {
        throw Throwables.propagate(e);
    }
    this.charset = Preconditions.checkNotNull(charset, "'charset' can NOT be null");
}

From source file:com.brienwheeler.svc.email.impl.EmailService.java

/**
 * This is a private method (rather than having the public template method
 * call the public non-template method) to prevent inaccurate MonitoredWork
 * operation counts.//from   w  w w .  j a  v  a  2  s  .co  m
 * 
 * @param recipient
 * @param subject
 * @param body
 */
private void doSendEmail(EmailAddress recipient, String subject, String body) {
    ValidationUtils.assertNotNull(recipient, "recipient cannot be null");
    subject = ValidationUtils.assertNotEmpty(subject, "subject cannot be empty");
    body = ValidationUtils.assertNotEmpty(body, "body cannot be empty");

    try {
        MimeMessage message = new MimeMessage(mailSession);
        message.setFrom(new InternetAddress(fromAddress.getAddress()));
        message.setRecipients(Message.RecipientType.TO, recipient.getAddress());
        message.setSubject(subject);
        message.setSentDate(new Date());
        message.setText(body);
        Transport.send(message);
        log.info("sent email to " + recipient.getAddress() + " (" + subject + ")");
    } catch (MessagingException e) {
        throw new ServiceOperationException(e);
    }
}

From source file:io.uengine.mail.MailAsyncService.java

@Async
public void registe(Long userId, String token, String subject, String fromUser, String fromName,
        final String toUser, InternetAddress[] toCC) {
    Session session = setMailProperties(toUser);

    Map model = new HashMap();
    model.put("link", MessageFormatter.arrayFormat("http://www.uengine.io/registe/confirm?userid={}&token={}",
            new Object[] { Long.toString(userId), token }).getMessage());

    String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail/registe.vm", "UTF-8",
            model);/*  w  w w.  j  a  v  a 2s .c  o m*/

    try {
        InternetAddress from = new InternetAddress(fromUser, fromName);
        MimeMessage message = new MimeMessage(session);
        message.setFrom(from);
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser));
        message.setSubject(subject);
        message.setContent(body, "text/html; charset=utf-8");
        if (toCC != null && toCC.length > 0)
            message.setRecipients(Message.RecipientType.CC, toCC);

        Transport.send(message);

        logger.info("{} ? ?? .", toUser);
    } catch (Exception e) {
        throw new ServiceException("??   .", e);
    }
}

From source file:mitm.application.djigzo.james.matchers.HasValidPasswordTest.java

@Test
public void testCaseInsensitive() throws MessagingException, EncryptorException {
    HasValidPassword matcher = new HasValidPassword();

    MockMatcherConfig matcherConfig = new MockMatcherConfig("test", "matchOnError=false", mailetContext);

    matcher.init(matcherConfig);/*from w w w.  j a v  a  2  s  . c o m*/

    Mail mail = new MockMail();

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.setContent("test", "text/plain");
    message.setFrom(new InternetAddress("123456@example.com"));

    message.saveChanges();

    mail.setMessage(message);

    Collection<MailAddress> recipients = new LinkedList<MailAddress>();

    recipients.add(new MailAddress("TEST2@EXAMPLE.COM"));

    mail.setRecipients(recipients);

    Collection<?> result = matcher.match(mail);

    assertEquals(1, result.size());
    assertTrue(result.contains(new MailAddress("TEST2@EXAMPLE.COM")));

    DjigzoMailAttributes attributes = new DjigzoMailAttributesImpl(mail);

    Passwords passwords = attributes.getPasswords();

    assertNotNull(passwords);
    assertNotNull(passwords.get("test2@example.com"));
    assertEquals("test2", passwords.get("test2@example.com").getPassword());
    assertEquals("ID2", passwords.get("test2@example.com").getPasswordID());
}

From source file:com.waveerp.sendMail.java

public void sendMsgSSL(String strSource, String strSourceDesc, String strSubject, String strMsg,
        String strDestination, String strDestDesc) throws Exception {

    // Call the registry management system                    
    registrySystem rs = new registrySystem();
    // Call the encryption management system
    desEncryption de = new desEncryption();
    de.Encrypter("", "");

    String strHost = rs.readRegistry("NA", "NA", "NA", "EMAILHOST");
    String strPort = rs.readRegistry("NA", "NA", "NA", "EMAILPORT");
    final String strUser = rs.readRegistry("NA", "NA", "NA", "EMAILUSER");
    String strPass = rs.readRegistry("NA", "NA", "NA", "EMAILPASSWORD");

    //Decrypt the encrypted password.
    final String strPass01 = de.decrypt(strPass);

    Properties props = new Properties();
    props.put("mail.smtp.host", strHost);
    props.put("mail.smtp.socketFactory.port", strPort);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", strPort);

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(strUser, strPass01);
        }/*from   w  ww . j av  a 2s .c  o m*/
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(strSource));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(strDestination));
        message.setSubject(strSubject);
        message.setText(strMsg);

        Transport.send(message);

        //System.out.println("Done");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }

    //log(DEBUG, strHost + "|" + strPort + "|" + strUser + "|" + strPass );

}

From source file:ch.entwine.weblounge.kernel.mail.SmtpService.java

/**
 * Creates a new message.
 * 
 * @return the new message
 */
public MimeMessage createMessage() {
    return new MimeMessage(getSession());
}

From source file:davmail.smtp.TestSmtp.java

public void testComplexToMessage() throws IOException, MessagingException, InterruptedException {
    String body = "Test message";
    MimeMessage mimeMessage = new MimeMessage((Session) null);
    mimeMessage.addHeader("To", "nickname <" + Settings.getProperty("davmail.to") + '>');
    mimeMessage.setSubject("Test subject");
    mimeMessage.setText(body);/*from w  w w . j  a  v a  2s . c om*/
    sendAndCheckMessage(mimeMessage);
}

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void SendEmailAnda(String from, String to1, String subject, String filename)
        throws FileNotFoundException, IOException {
    //Get properties object    
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");
    //get Session   
    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(from, "anda.cristea");
        }/*w  w  w  .ja va 2s  . co  m*/
    });
    //compose message    
    try {
        MimeMessage message = new MimeMessage(session);
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to1));

        message.setSubject(subject);
        // message.setText(msg);

        BodyPart messageBodyPart = new MimeBodyPart();

        messageBodyPart.setText("Raport teste automate");

        Multipart multipart = new MimeMultipart();

        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();

        DataSource source = new FileDataSource(filename);

        messageBodyPart.setDataHandler(new DataHandler(source));

        messageBodyPart.setFileName(filename);

        multipart.addBodyPart(messageBodyPart);

        //message.setContent(multipart);

        StringWriter writer = new StringWriter();
        IOUtils.copy(new FileInputStream(new File(filename)), writer);

        message.setContent(writer.toString(), "text/html");

        //send message  
        Transport.send(message);

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }

}

From source file:de.mendelson.comm.as2.message.AS2MessageCreation.java

/**Enwrapps the data into a signed MIME message structure and returns it*/
private void enwrappInMessageAndSign(AS2Message message, Part contentPart, Partner sender, Partner receiver)
        throws Exception {
    AS2MessageInfo info = (AS2MessageInfo) message.getAS2Info();
    MimeMessage messagePart = new MimeMessage(Session.getInstance(System.getProperties(), null));
    //sign message if this is requested
    if (info.getSignType() != AS2Message.SIGNATURE_NONE) {
        MimeMultipart signedPart = this.signContentPart(contentPart, sender, receiver);
        if (this.logger != null) {
            String signAlias = this.signatureCertManager.getAliasByFingerprint(sender.getSignFingerprintSHA1());
            this.logger.log(Level.INFO,
                    this.rb.getResourceString("message.signed",
                            new Object[] { info.getMessageId(), signAlias,
                                    this.rbMessage.getResourceString("signature." + receiver.getSignType()) }),
                    info);/*from  w ww .jav  a  2s . c o m*/
        }
        messagePart.setContent(signedPart);
        messagePart.saveChanges();
    } else {
        //unsigned message
        if (contentPart instanceof MimeBodyPart) {
            MimeMultipart unsignedPart = new MimeMultipart();
            unsignedPart.addBodyPart((MimeBodyPart) contentPart);
            if (this.logger != null) {
                this.logger.log(Level.INFO,
                        this.rb.getResourceString("message.notsigned", new Object[] { info.getMessageId() }),
                        info);
            }
            messagePart.setContent(unsignedPart);
        } else if (contentPart instanceof MimeMultipart) {
            messagePart.setContent((MimeMultipart) contentPart);
        } else if (contentPart instanceof MimeMessage) {
            messagePart = (MimeMessage) contentPart;
        } else {
            throw new IllegalArgumentException("enwrappInMessageAndSign: Unable to set the content of a "
                    + contentPart.getClass().getName());
        }
        messagePart.saveChanges();
    }
    //store signed or unsigned data
    ByteArrayOutputStream signedOut = new ByteArrayOutputStream();
    //normally the content type header is folded (which is correct but some products are not able to parse this properly)
    //Now take the content-type, unfold it and write it
    Enumeration headerLines = messagePart.getMatchingHeaderLines(new String[] { "Content-Type" });
    LineOutputStream los = new LineOutputStream(signedOut);
    while (headerLines.hasMoreElements()) {
        //requires java mail API >= 1.4
        String nextHeaderLine = MimeUtility.unfold((String) headerLines.nextElement());
        //write the line only if the as2 message is encrypted. If the as2 message is unencrypted this header is added later
        //in the class MessageHttpUploader
        if (info.getEncryptionType() != AS2Message.ENCRYPTION_NONE) {
            los.writeln(nextHeaderLine);
        }
        //store the content line in the as2 message object, this value is required later in MessageHttpUploader
        message.setContentType(nextHeaderLine.substring(nextHeaderLine.indexOf(':') + 1));
    }
    messagePart.writeTo(signedOut, new String[] { "Message-ID", "Mime-Version", "Content-Type" });
    signedOut.flush();
    signedOut.close();
    message.setDecryptedRawData(signedOut.toByteArray());
}

From source file:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java

protected void createInitialIMAPTestdata(final Properties props, final String user, final String password,
        final int count, final boolean deleteall) throws MessagingException {
    final Session session = Session.getInstance(props);
    final Store store = session.getStore();
    store.connect(user, password);/*from w  w w.  ja  v  a  2  s . co  m*/
    checkStoreForTestConnection(store);
    final Folder root = store.getDefaultFolder();
    final Folder testroot = root.getFolder("ES-IMAP-RIVER-TESTS");
    final Folder testrootl2 = testroot.getFolder("Level(2!");

    if (deleteall) {

        deleteMailsFromUserMailbox(props, "INBOX", 0, -1, user, password);

        if (testroot.exists()) {
            testroot.delete(true);
        }

        final Folder testrootenamed = root.getFolder("renamed_from_ES-IMAP-RIVER-TESTS");
        if (testrootenamed.exists()) {
            testrootenamed.delete(true);
        }

    }

    if (!testroot.exists()) {

        testroot.create(Folder.HOLDS_FOLDERS & Folder.HOLDS_MESSAGES);
        testroot.open(Folder.READ_WRITE);

        testrootl2.create(Folder.HOLDS_FOLDERS & Folder.HOLDS_MESSAGES);
        testrootl2.open(Folder.READ_WRITE);

    }

    final Folder inbox = root.getFolder("INBOX");
    inbox.open(Folder.READ_WRITE);

    final Message[] msgs = new Message[count];

    for (int i = 0; i < count; i++) {
        final MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(EMAIL_TO));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(EMAIL_USER_ADDRESS));
        message.setSubject(EMAIL_SUBJECT + "::" + i);
        message.setText(EMAIL_TEXT + "::" + SID++);
        message.setSentDate(new Date());
        msgs[i] = message;

    }

    inbox.appendMessages(msgs);
    testroot.appendMessages(msgs);
    testrootl2.appendMessages(msgs);

    IMAPUtils.close(inbox);
    IMAPUtils.close(testrootl2);
    IMAPUtils.close(testroot);
    IMAPUtils.close(store);

}