Search in sources :

Example 61 with Message

use of javax.mail.Message in project jmeter by apache.

the class SendMailCommand method prepareMessage.

/**
     * Prepares message prior to be sent via execute()-method, i.e. sets
     * properties such as protocol, authentication, etc.
     *
     * @return Message-object to be sent to execute()-method
     * @throws MessagingException
     *             when problems constructing or sending the mail occur
     * @throws IOException
     *             when the mail content can not be read or truststore problems
     *             are detected
     */
public Message prepareMessage() throws MessagingException, IOException {
    Properties props = new Properties();
    String protocol = getProtocol();
    // set properties using JAF
    props.setProperty("mail." + protocol + ".host", smtpServer);
    props.setProperty("mail." + protocol + ".port", getPort());
    props.setProperty("mail." + protocol + ".auth", Boolean.toString(useAuthentication));
    // set timeout
    props.setProperty("mail." + protocol + ".timeout", getTimeout());
    props.setProperty("mail." + protocol + ".connectiontimeout", getConnectionTimeout());
    if (useStartTLS || useSSL) {
        try {
            String allProtocols = StringUtils.join(SSLContext.getDefault().getSupportedSSLParameters().getProtocols(), " ");
            logger.info("Use ssl/tls protocols for mail: " + allProtocols);
            props.setProperty("mail." + protocol + ".ssl.protocols", allProtocols);
        } catch (Exception e) {
            logger.error("Problem setting ssl/tls protocols for mail", e);
        }
    }
    if (enableDebug) {
        props.setProperty("mail.debug", "true");
    }
    if (useStartTLS) {
        props.setProperty("mail.smtp.starttls.enable", "true");
        if (enforceStartTLS) {
            // Requires JavaMail 1.4.2+
            props.setProperty("mail.smtp.starttls.require", "true");
        }
    }
    if (trustAllCerts) {
        if (useSSL) {
            props.setProperty("mail.smtps.ssl.socketFactory.class", TRUST_ALL_SOCKET_FACTORY);
            props.setProperty("mail.smtps.ssl.socketFactory.fallback", "false");
        } else if (useStartTLS) {
            props.setProperty("mail.smtp.ssl.socketFactory.class", TRUST_ALL_SOCKET_FACTORY);
            props.setProperty("mail.smtp.ssl.socketFactory.fallback", "false");
        }
    } else if (useLocalTrustStore) {
        File truststore = new File(trustStoreToUse);
        logger.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath());
        if (!truststore.exists()) {
            logger.info("load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath());
            truststore = new File(FileServer.getFileServer().getBaseDir(), trustStoreToUse);
            logger.info("load local truststore -Attempting to read truststore from:  " + truststore.getAbsolutePath());
            if (!truststore.exists()) {
                logger.info("load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath() + ". Local truststore not available, aborting execution.");
                throw new IOException("Local truststore file not found. Also not available under : " + truststore.getAbsolutePath());
            }
        }
        if (useSSL) {
            // Requires JavaMail 1.4.2+
            props.put("mail.smtps.ssl.socketFactory", new LocalTrustStoreSSLSocketFactory(truststore));
            props.put("mail.smtps.ssl.socketFactory.fallback", "false");
        } else if (useStartTLS) {
            // Requires JavaMail 1.4.2+
            props.put("mail.smtp.ssl.socketFactory", new LocalTrustStoreSSLSocketFactory(truststore));
            props.put("mail.smtp.ssl.socketFactory.fallback", "false");
        }
    }
    session = Session.getInstance(props, null);
    Message message;
    if (sendEmlMessage) {
        message = new MimeMessage(session, new BufferedInputStream(new FileInputStream(emlMessage)));
    } else {
        message = new MimeMessage(session);
        // handle body and attachments
        Multipart multipart = new MimeMultipart();
        final int attachmentCount = attachments.size();
        if (plainBody && (attachmentCount == 0 || (mailBody.length() == 0 && attachmentCount == 1))) {
            if (attachmentCount == 1) {
                // i.e. mailBody is empty
                File first = attachments.get(0);
                try (FileInputStream fis = new FileInputStream(first);
                    InputStream is = new BufferedInputStream(fis)) {
                    message.setText(IOUtils.toString(is, Charset.defaultCharset()));
                }
            } else {
                message.setText(mailBody);
            }
        } else {
            BodyPart body = new MimeBodyPart();
            body.setText(mailBody);
            multipart.addBodyPart(body);
            for (File f : attachments) {
                BodyPart attach = new MimeBodyPart();
                attach.setFileName(f.getName());
                attach.setDataHandler(new DataHandler(new FileDataSource(f.getAbsolutePath())));
                multipart.addBodyPart(attach);
            }
            message.setContent(multipart);
        }
    }
    // set from field and subject
    if (null != sender) {
        message.setFrom(new InternetAddress(sender));
    }
    if (null != replyTo) {
        InternetAddress[] to = new InternetAddress[replyTo.size()];
        message.setReplyTo(replyTo.toArray(to));
    }
    if (null != subject) {
        message.setSubject(subject);
    }
    if (receiverTo != null) {
        InternetAddress[] to = new InternetAddress[receiverTo.size()];
        receiverTo.toArray(to);
        message.setRecipients(Message.RecipientType.TO, to);
    }
    if (receiverCC != null) {
        InternetAddress[] cc = new InternetAddress[receiverCC.size()];
        receiverCC.toArray(cc);
        message.setRecipients(Message.RecipientType.CC, cc);
    }
    if (receiverBCC != null) {
        InternetAddress[] bcc = new InternetAddress[receiverBCC.size()];
        receiverBCC.toArray(bcc);
        message.setRecipients(Message.RecipientType.BCC, bcc);
    }
    for (int i = 0; i < headerFields.size(); i++) {
        Argument argument = (Argument) headerFields.get(i).getObjectValue();
        message.setHeader(argument.getName(), argument.getValue());
    }
    message.saveChanges();
    return message;
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) Multipart(javax.mail.Multipart) MimeMultipart(javax.mail.internet.MimeMultipart) InternetAddress(javax.mail.internet.InternetAddress) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) Argument(org.apache.jmeter.config.Argument) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) DataHandler(javax.activation.DataHandler) Properties(java.util.Properties) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) MimeMessage(javax.mail.internet.MimeMessage) BufferedInputStream(java.io.BufferedInputStream) MimeMultipart(javax.mail.internet.MimeMultipart) FileDataSource(javax.activation.FileDataSource) MimeBodyPart(javax.mail.internet.MimeBodyPart) File(java.io.File)

Example 62 with Message

use of javax.mail.Message in project jmeter by apache.

the class SmtpSampler method sample.

/**
     * Performs the sample, and returns the result
     *
     * @param e Standard-method-header from JMeter
     * @return Result of the sample
     * @see org.apache.jmeter.samplers.Sampler#sample(org.apache.jmeter.samplers.Entry)
     */
@Override
public SampleResult sample(Entry e) {
    SendMailCommand sendMailCmd;
    Message message;
    SampleResult result = createSampleResult();
    try {
        sendMailCmd = createSendMailCommandFromProperties();
        message = sendMailCmd.prepareMessage();
        result.setBytes(calculateMessageSize(message));
    } catch (Exception ex) {
        log.warn("Error while preparing message", ex);
        result.setResponseCode("500");
        result.setResponseMessage(ex.toString());
        return result;
    }
    // Set up the sample result details
    result.setDataType(SampleResult.TEXT);
    try {
        result.setRequestHeaders(getRequestHeaders(message));
        result.setSamplerData(getSamplerData(message));
    } catch (MessagingException | IOException ex) {
        result.setSamplerData("Error occurred trying to save request info: " + ex);
        log.warn("Error occurred trying to save request info", ex);
    }
    // Perform the sampling
    result.sampleStart();
    boolean isSuccessful = executeMessage(result, sendMailCmd, message);
    result.sampleEnd();
    try {
        result.setResponseData(processSampler(message));
    } catch (IOException | MessagingException ex) {
        log.warn("Failed to set result response data", ex);
    }
    result.setSuccessful(isSuccessful);
    return result;
}
Also used : Message(javax.mail.Message) MessagingException(javax.mail.MessagingException) SampleResult(org.apache.jmeter.samplers.SampleResult) IOException(java.io.IOException) SendMailCommand(org.apache.jmeter.protocol.smtp.sampler.protocol.SendMailCommand) MessagingException(javax.mail.MessagingException) AuthenticationFailedException(javax.mail.AuthenticationFailedException) AddressException(javax.mail.internet.AddressException) IOException(java.io.IOException)

Example 63 with Message

use of javax.mail.Message in project jmeter by apache.

the class MailerModel method sendMail.

/**
     * Sends a mail with the given parameters using SMTP.
     *
     * @param from
     *            the sender of the mail as shown in the mail-client.
     * @param vEmails
     *            all receivers of the mail. The receivers are seperated by
     *            commas.
     * @param subject
     *            the subject of the mail.
     * @param attText
     *            the message-body.
     * @param smtpHost
     *            the smtp-server used to send the mail.
     * @param smtpPort the smtp-server port used to send the mail.
     * @param user the login used to authenticate
     * @param password the password used to authenticate
     * @param mailAuthType {@link MailAuthType} Security policy
     * @param debug Flag whether debug messages for the mail session should be generated
     * @throws AddressException If mail address is wrong
     * @throws MessagingException If building MimeMessage fails
     */
public void sendMail(String from, List<String> vEmails, String subject, String attText, String smtpHost, String smtpPort, final String user, final String password, MailAuthType mailAuthType, boolean debug) throws MessagingException {
    InternetAddress[] address = new InternetAddress[vEmails.size()];
    for (int k = 0; k < vEmails.size(); k++) {
        address[k] = new InternetAddress(vEmails.get(k));
    }
    // create some properties and get the default Session
    Properties props = new Properties();
    props.put(MAIL_SMTP_HOST, smtpHost);
    // property values are strings
    props.put(MAIL_SMTP_PORT, smtpPort);
    Authenticator authenticator = null;
    if (mailAuthType != MailAuthType.NONE) {
        props.put(MAIL_SMTP_AUTH, "true");
        switch(mailAuthType) {
            case SSL:
                props.put(MAIL_SMTP_SOCKETFACTORY_CLASS, "javax.net.ssl.SSLSocketFactory");
                break;
            case TLS:
                props.put(MAIL_SMTP_STARTTLS, "true");
                break;
            default:
                break;
        }
    }
    if (!StringUtils.isEmpty(user)) {
        authenticator = new javax.mail.Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, password);
            }
        };
    }
    Session session = Session.getInstance(props, authenticator);
    session.setDebug(debug);
    // create a message
    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(from));
    msg.setRecipients(Message.RecipientType.TO, address);
    msg.setSubject(subject);
    msg.setText(attText);
    Transport.send(msg);
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) MimeMessage(javax.mail.internet.MimeMessage) Properties(java.util.Properties) Authenticator(javax.mail.Authenticator) Authenticator(javax.mail.Authenticator) PasswordAuthentication(javax.mail.PasswordAuthentication) Session(javax.mail.Session)

Example 64 with Message

use of javax.mail.Message in project smartmodule by carozhu.

the class JavaEmail method sendEmailBUGForDevloper.

public static void sendEmailBUGForDevloper(String formApp, Throwable e, String email, String emailPassword) throws AddressException, MessagingException {
    Properties properties = new Properties();
    // Send mail	// protocol
    properties.setProperty("mail.transport.protocol", "smtp");
    // Need to verify
    properties.setProperty("mail.smtp.auth", "true");
    //Background debug mode
    properties.setProperty("mail.debug", "true");
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.host", "smtp.qq.com");
    properties.put("mail.smtp.port", "220");
    MyAuthenticator smyauth = new MyAuthenticator(email, emailPassword);
    // setup process output messages sent
    Session session = Session.getInstance(properties, smyauth);
    // debug mode
    session.setDebug(true);
    // Email message
    Message messgae = new MimeMessage(session);
    // set sender
    messgae.setFrom(new InternetAddress(email));
    // set the messgae content
    messgae.setText(getErrorInfoFromException(e));
    System.out.println(getErrorInfoFromException(e));
    Date now = new Date();
    //可以方便地修改日期格式
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    String hehe = dateFormat.format(now);
    // set the message subject
    messgae.setSubject("author:caro-->recv" + formApp + "   异常反馈,时间:" + hehe);
    // Send e-mail
    Transport tran = session.getTransport();
    // tran.connect("smtp.sohu.com", 25, "xxx@sohu.com", "xxxx");//sohu-mail
    // server to connect to
    // tran.connect("smtp.sina.com", 25, "xxx@sina.cn",
    // "xxxxxxx");//Sina-mail server to connect to
    // tran.connect("smtp.qq.com", 25, "xxx@qq.com", "xxxx");//qq-mail
    // server to connect to
    tran.connect("smtp.qq.com", 25, email, emailPassword);
    // Set// mail// recipient (email)  test:2376323219@qq.com  452262448@qq.com  1025807062@qq.com
    tran.sendMessage(messgae, new Address[] { new InternetAddress("1025807062@qq.com") });
    tran.close();
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) MimeMessage(javax.mail.internet.MimeMessage) Properties(java.util.Properties) Transport(javax.mail.Transport) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date) Session(javax.mail.Session)

Example 65 with Message

use of javax.mail.Message in project Gargoyle by callakrsos.

the class EmailAttachmentSender method sendEmailWithAttachments.

public static void sendEmailWithAttachments(String host, String port, final String userName, final String password, String toAddress, String subject, String message, String[] attachFiles) throws AddressException, MessagingException {
    // sets SMTP server properties
    Properties properties = new Properties();
    properties.put("mail.smtp.host", host);
    properties.put("mail.smtp.port", port);
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.user", userName);
    properties.put("mail.password", password);
    // creates a new session with an authenticator
    Authenticator auth = new Authenticator() {

        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password);
        }
    };
    Session session = Session.getInstance(properties, auth);
    // creates a new e-mail message
    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(userName));
    InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
    msg.setRecipients(Message.RecipientType.TO, toAddresses);
    msg.setSubject(subject);
    msg.setSentDate(new Date());
    // creates message part
    MimeBodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setContent(message, "text/html");
    // creates multi-part
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);
    // adds attachments
    if (attachFiles != null && attachFiles.length > 0) {
        for (String filePath : attachFiles) {
            MimeBodyPart attachPart = new MimeBodyPart();
            try {
                attachPart.attachFile(filePath);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            multipart.addBodyPart(attachPart);
        }
    }
    // sets the multi-part as e-mail's content
    msg.setContent(multipart);
    // sends the e-mail
    Transport.send(msg);
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) IOException(java.io.IOException) Properties(java.util.Properties) Date(java.util.Date) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart) Authenticator(javax.mail.Authenticator) PasswordAuthentication(javax.mail.PasswordAuthentication) 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