Example usage for org.apache.commons.net.smtp SimpleSMTPHeader addHeaderField

List of usage examples for org.apache.commons.net.smtp SimpleSMTPHeader addHeaderField

Introduction

In this page you can find the example usage for org.apache.commons.net.smtp SimpleSMTPHeader addHeaderField.

Prototype

public void addHeaderField(String headerField, String value) 

Source Link

Document

Adds an arbitrary header field with the given value to the article header.

Usage

From source file:ca.rmen.android.networkmonitor.app.email.Emailer.java

/**
 * Sends an e-mail in UTF-8 encoding.//from   w  w w.j a  v a  2s. c  om
 *
 * @param protocol    this has been tested with "TLS", "SSL", and null.
 * @param attachments optional attachments to include in the mail.
 * @param debug       if true, details about the smtp commands will be logged to stdout.
 */
static void sendEmail(String protocol, String server, int port, String user, String password, String from,
        String[] recipients, String subject, String body, Set<File> attachments, boolean debug)
        throws Exception {

    // Set up the mail connectivity
    final AuthenticatingSMTPClient client;
    if (protocol == null)
        client = new AuthenticatingSMTPClient();
    else
        client = new AuthenticatingSMTPClient(protocol);

    if (debug)
        client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

    client.setDefaultTimeout(SMTP_TIMEOUT_MS);
    client.setCharset(Charset.forName(ENCODING));
    client.connect(server, port);
    checkReply(client);
    client.helo("[" + client.getLocalAddress().getHostAddress() + "]");
    checkReply(client);
    if ("TLS".equals(protocol)) {
        if (!client.execTLS()) {
            checkReply(client);
            throw new RuntimeException("Could not start tls");
        }
    }
    client.auth(AuthenticatingSMTPClient.AUTH_METHOD.LOGIN, user, password);
    checkReply(client);

    // Set up the mail participants
    client.setSender(from);
    checkReply(client);
    for (String recipient : recipients) {
        client.addRecipient(recipient);
        checkReply(client);
    }

    // Set up the mail content
    Writer writer = client.sendMessageData();
    SimpleSMTPHeader header = new SimpleSMTPHeader(from, recipients[0], subject);
    for (int i = 1; i < recipients.length; i++)
        header.addCC(recipients[i]);

    // Just plain text mail: no attachments
    if (attachments == null || attachments.isEmpty()) {
        header.addHeaderField("Content-Type", "text/plain; charset=" + ENCODING);
        writer.write(header.toString());
        writer.write(body);
    }
    // Mail with attachments
    else {
        String boundary = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 28);
        header.addHeaderField("Content-Type", "multipart/mixed; boundary=" + boundary);
        writer.write(header.toString());

        // Write the main text message
        writer.write("--" + boundary + "\n");
        writer.write("Content-Type: text/plain; charset=" + ENCODING + "\n\n");
        writer.write(body);
        writer.write("\n");

        // Write the attachments
        appendAttachments(writer, boundary, attachments);
        writer.write("--" + boundary + "--\n\n");
    }

    writer.close();
    if (!client.completePendingCommand()) {
        throw new RuntimeException("Could not send mail");
    }
    client.logout();
    client.disconnect();
}

From source file:adams.core.net.ApacheSendEmail.java

/**
 * Sends an email./*  w ww .  j  a  va 2  s.  c  o m*/
 *
 * @param email   the email to send
 * @return      true if successfully sent
 * @throws Exception   in case of invalid internet addresses or messaging problem
 */
@Override
public boolean sendMail(Email email) throws Exception {
    SimpleSMTPHeader header;
    int i;
    Writer writer;
    String boundary;
    MediaType mime;
    byte[] content;
    String[] lines;

    if (m_Client == null)
        throw new IllegalStateException("SMTP session not initialized!");

    // header
    header = new SimpleSMTPHeader(email.getFrom().getValue(), Utils.flatten(email.getTo(), ", "),
            email.getSubject());
    for (i = 0; i < email.getCC().length; i++)
        header.addCC(email.getCC()[i].getValue());

    // create boundary string
    boundary = EmailHelper.createBoundary();
    header.addHeaderField("Content-Type", "multipart/mixed; boundary=" + boundary);

    // connect
    m_Client.connect(m_Server, m_Port);
    if (!SMTPReply.isPositiveCompletion(m_Client.getReplyCode())) {
        m_Client.disconnect();
        getLogger().severe(
                "SMTP server " + m_Server + ":" + m_Port + " refused connection: " + m_Client.getReplyCode());
        return false;
    }

    // login
    if (!m_Client.login()) {
        m_Client.disconnect();
        getLogger().severe("Failed to login to SMTP server " + m_Server + ":" + m_Port + "!");
        return false;
    }

    // TLS?
    if (m_UseTLS) {
        if (!((SMTPSClient) m_Client).execTLS()) {
            m_Client.logout();
            m_Client.disconnect();
            getLogger().severe("SMTP server " + m_Server + ":" + m_Port + " failed to start TLS!");
            return false;
        }
    }

    // authentication?
    if (m_RequiresAuth) {
        if (!((AuthenticatingSMTPClient) m_Client).auth(AuthenticatingSMTPClient.AUTH_METHOD.PLAIN, m_User,
                m_Password.getValue())) {
            m_Client.logout();
            m_Client.disconnect();
            getLogger()
                    .severe("Failed to authenticate: user=" + m_User + ", pw=" + m_Password.getMaskedValue());
            return false;
        }
    }

    // fill in recipients
    m_Client.setSender(email.getFrom().stringValue());
    for (i = 0; i < email.getTo().length; i++)
        m_Client.addRecipient(email.getTo()[i].getValue());
    for (i = 0; i < email.getCC().length; i++)
        m_Client.addRecipient(email.getCC()[i].strippedValue());
    for (i = 0; i < email.getBCC().length; i++)
        m_Client.addRecipient(email.getBCC()[i].stringValue());

    // start message
    writer = m_Client.sendMessageData();
    if (writer == null) {
        m_Client.logout();
        m_Client.disconnect();
        getLogger().severe("Cannot send data!");
        return false;
    }
    writer.write(header.toString());

    // body
    writer.write("--" + boundary + "\n");
    writer.write("Content-Type: text/plain; charset=ISO-8859-1\n");
    writer.write("\n");
    writer.write(email.getBody());
    writer.write("\n");
    writer.write("\n");

    // attachements
    if (email.getAttachments().length > 0) {
        for (File file : email.getAttachments()) {
            writer.write("--" + boundary + "\n");
            mime = MimeTypeHelper.getMimeType(file);
            writer.write("Content-Type: " + mime.toString() + "; name=\"" + file.getName() + "\"\n");
            writer.write("Content-Disposition: attachment; filename=\"" + file.getName() + "\"\n");
            writer.write("Content-Transfer-Encoding: base64\n");
            writer.write("\n");
            content = FileUtils.loadFromBinaryFile(file);
            lines = EmailHelper.breakUp(InternetHelper.encodeBase64(content), 76);
            for (String line : lines)
                writer.write(line + "\n");
        }
    }

    // finish message
    writer.write("--" + boundary + "--\n");
    writer.close();

    if (!m_Client.completePendingCommand()) {
        m_Client.logout();
        m_Client.disconnect();
        getLogger().severe("Failed to complete pending command!");
        return false;
    }

    m_Client.logout();
    m_Client.disconnect();

    return true;
}