使用Javamail jar向android中的多个用户发送电子邮件

时间:2014-01-29 10:50:09

标签: android javamail

我正在设计一款Android应用,允许用户向朋友发送邀请。

我正在使用Javamail jar进行此过程。

一切正常。但是,我希望能够同时向多个用户发送邀请,同时修改每个被邀请者的电子邮件正文。使用BCC或CC将不起作用,因为身体永远不会相同。

在我的AsyncTask中,我循环遍历TO地址列表并一次发送一封电子邮件。但是,问题是当发送第一封电子邮件时,假设在第二封邮件正文中的项目包含在第一封邮件中,从而丢弃了第一封邮件中假设的一些邮件。

请问我该如何解决这个问题?

我的代码:

private class SendEmailTask extends AsyncTask<Void, Void, Boolean> {

    private ProgressDialog dialog;

    public SendEmailTask() {
        dialog = new ProgressDialog(_context);
    }

    protected void onPreExecute() {
        dialog.setMessage("Sending");
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setCancelable(false);
        dialog.setIndeterminate(true);
        dialog.show();
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        boolean result = false;
        String to = "";
        try {
            String body = setting.parseAsset(_context, "email.html");
            String name = _session.getDisplayName();

            body = body.replace("<%NAME%>", name);
            if (items.size() > 0) {
                Mail mail = null; 

                for (String to: items) {            
                    mail = new Mail("test@gmail.com",
                            "Thisisatest1");
                    body = body.replace("<%EMAIL%>", to);

                    mail.set_to(to);
                    mail.set_from("no-reply@test.com");
                    mail.set_subject(name + " has invited you to Test");
                    mail.set_body(body);

                    result = mail.send();
                }

            }

            return result;
        } catch (Exception e) {
            Log.e("SendEmailTask", "Invite not sent to " + to, e);
            dialog.dismiss();
            return false;
        }
    }

    @Override
    protected void onPostExecute(Boolean result) {
        dialog.dismiss();
        if (result) {
            Toast.makeText(_context, "Invite sent successfully.",
                    Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getApplicationContext(), "Invite(s) not sent.",
                    Toast.LENGTH_LONG).show();
        }
    }

}


public class Mail extends Authenticator{

private String _user;
private String _password;
private String _to;
private String _from;
private String _port;
private String _socket;
private String _host;
private String _subject;
private String _body;
private boolean _auth;
private boolean _debuggable;
private Multipart _multipart;

public String getUser() {
    return _user;
}
public void setUser(String user) {
    this._user = user;
}
public String getPassword() {
    return _password;
}
public void setPassword(String password) {
    this._password = password;
}
public String get_to() {
    return _to;
}
public void set_to(String _to) {
    this._to = _to;
}
public String get_from() {
    return _from;
}
public void set_from(String _from) {
    this._from = _from;
}
public String get_port() {
    return _port;
}
public void set_port(String _port) {
    this._port = _port;
}
public String get_socket() {
    return _socket;
}
public void set_socket(String _socket) {
    this._socket = _socket;
}
public String get_host() {
    return _host;
}
public void set_host(String _host) {
    this._host = _host;
}
public String get_subject() {
    return _subject;
}
public void set_subject(String _subject) {
    this._subject = _subject;
}
public String get_body() {
    return _body;
}
public void set_body(String _body) {
    this._body = _body;
}
public boolean is_auth() {
    return _auth;
}
public void set_auth(boolean _auth) {
    this._auth = _auth;
}
public boolean is_debuggable() {
    return _debuggable;
}
public void set_debuggable(boolean _debuggable) {
    this._debuggable = _debuggable;
}
public Multipart get_multipart() {
    return _multipart;
}
public void set_multipart(Multipart _multipart) {
    this._multipart = _multipart;
}

public Mail() {
    _host = "smtp.gmail.com"; // default smtp server
    _port = "465"; // default smtp port
    _socket = "465"; // default socketfactory port

    _user = ""; // username
    _password = ""; // password
    _from = ""; // email sent from
    _subject = ""; // email subject
    _body = ""; // email body

    _debuggable = false; // debug mode on or off - default off
    _auth = true; // smtp authentication - default on

    _multipart = new MimeMultipart();

    // There is something wrong with MailCap, javamail can not find a
    // handler for the multipart/mixed part, so this bit needs to be added.
    MailcapCommandMap mailCap = (MailcapCommandMap) CommandMap
            .getDefaultCommandMap();
    mailCap.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
    mailCap.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
    mailCap.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
    mailCap.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
    mailCap.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
    CommandMap.setDefaultCommandMap(mailCap);
}

public Mail(String user, String pass) {
    this();
    this._user = user;
    this._password = pass;
}

public boolean send() throws Exception {
    Properties props = setProperties();

    if (!_user.equals("") && !_password.equals("") && !_to.equals("")
            && !_from.equals("") && !_subject.equals("") && !_body.equals("")) {
        Session session = Session.getInstance(props, this);

        MimeMessage msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(_from));

        InternetAddress addressTo = new InternetAddress();
        addressTo.setAddress(_to);

        msg.setRecipient(MimeMessage.RecipientType.TO, addressTo);

        msg.setSubject(_subject);
        msg.setSentDate(new Date());

        // setup message body
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(_body);
        messageBodyPart.setHeader("Content-Type", "text/html");
        _multipart.addBodyPart(messageBodyPart);

        // Put parts in message
        msg.setContent(_multipart);

        msg.saveChanges();

        // send email
        Transport.send(msg);

        return true;
    } else {
        return false;
    }
}


@Override
public PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(_user, _password);
}

private Properties setProperties() {
    Properties props = new Properties();

    props.put("mail.smtp.host", _host);

    if (_debuggable) {
        props.put("mail.debug", "true");
    }

    if (_auth) {
        props.put("mail.smtp.auth", "true");
    }

    props.put("mail.smtp.port", _port);
    props.put("mail.smtp.socketFactory.port", _socket);
    props.put("mail.smtp.socketFactory.class",
            "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");

    return props;
}   
}

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

您的Mail类每次都会创建一个新的MimeMessage,每次都有新的MimeBodyParts,但每次都重复使用相同的MimeMultipart。

答案 1 :(得分:0)

通过在发送每封电子邮件后设置mail = null来修复它

for (InviteItem item : items) {
                    Mail mail = new Mail("test@test.com",
                            "MYPASSIFORGOTTOCHANGE");
                    to = ((com.plan.library.contact.Invite) item)
                            .get_email();
                    invitees.add(to);

                    String body = html.replace("<%EMAIL%>", to);

                    mail.set_to(to);
                    mail.set_from("test@test.com");
                    mail.set_subject(name + " has invited");
                    mail.set_body(body);

                    result = mail.send();
                    mail = null;
                }