从java Web应用程序发送邮件

时间:2014-11-20 05:57:05

标签: java email javax.mail

我正在开发一个可以发送电子邮件的网络应用程序。我正在使用javax mail api。我能够通过主题,发件人姓名,内容从测试用例发送电子邮件。但是当应用程序运行时,它会发送带有主题的消息,内容看起来像这样。

------=_Part_3_47905596.1416462380132
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 7bit

Test mail Send Succesfully
------=_Part_3_47905596.1416462380132--

这是我正在使用的代码。

Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
String subject = "Test Subject";
String msgContent = "Test mail Send Succesfully";
String senderName = "Jos";
String password = "XXXXXXXXXXX";
String fromEmail = "xxxxxxxxx@gmail.com";
String toEmail = "YYYYYYYYYYY@gmail.com";
Session session = Session.getInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(fromEmail, password);
                }
            });
Message message = new MimeMessage(session);
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText(msgContent, "utf-8");
Multipart multiPart = new MimeMultipart("alternative");
multiPart.addBodyPart(textPart);
message.setContent(multiPart);
message.setFrom(new InternetAddress(fromEmail, senderName));
message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse(toEmail));
message.setSubject(subject);
message.setSentDate(new Date());
Transport.send(message);

添加调试消息而不使用多部分

Loading javamail.default.providers from jar:file:/my-web/WEB-INF/lib/mail-1.4.7.jar!/META-INF/javamail.default.providers
DEBUG: loading new provider protocol=imap, className=com.sun.mail.imap.IMAPStore, vendor=Oracle, version=null
DEBUG: loading new provider protocol=imaps, className=com.sun.mail.imap.IMAPSSLStore, vendor=Oracle, version=null
DEBUG: loading new provider protocol=smtp, className=com.sun.mail.smtp.SMTPTransport, vendor=Oracle, version=null
DEBUG: loading new provider protocol=smtps, className=com.sun.mail.smtp.SMTPSSLTransport, vendor=Oracle, version=null
DEBUG: loading new provider protocol=pop3, className=com.sun.mail.pop3.POP3Store, vendor=Oracle, version=null
DEBUG: loading new provider protocol=pop3s, className=com.sun.mail.pop3.POP3SSLStore, vendor=Oracle, version=null
Loading javamail.default.providers from jar:file:/my-web/WEB-INF/lib/mail-1.4.jar!/META-INF/javamail.default.providers
DEBUG: loading new provider protocol=imap, className=com.sun.mail.imap.IMAPStore, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=imaps, className=com.sun.mail.imap.IMAPSSLStore, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=smtp, className=com.sun.mail.smtp.SMTPTransport, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=smtps, className=com.sun.mail.smtp.SMTPSSLTransport, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=pop3, className=com.sun.mail.pop3.POP3Store, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=pop3s, className=com.sun.mail.pop3.POP3SSLStore, vendor=Sun Microsystems, Inc, version=null
DEBUG: getProvider() returning provider protocol=smtp; type=javax.mail.Provider$Type@17c7ee05; class=com.sun.mail.smtp.SMTPTransport; vendor=Oracle
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 587, isSSL false
220 mx.google.com ESMTP uj7sm1724517pac.4 - gsmtp
DEBUG SMTP: connected to host "smtp.gmail.com", port: 587

EHLO localhost
250-mx.google.com at your service, [201.140.200.84]
250-SIZE 35882577
250-8BITMIME
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
STARTTLS
220 2.0.0 Ready to start TLS
EHLO localhost
250-mx.google.com at your service, [201.140.200.84]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER"
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
DEBUG SMTP: Attempt to authenticate using mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM 
DEBUG SMTP: AUTH LOGIN command trace suppressed
DEBUG SMTP: AUTH LOGIN succeeded
DEBUG SMTP: use8bit false
MAIL FROM:<xxxxxxxxxxx@gmail.com>
250 2.1.0 OK uj7sm1724517pac.4 - gsmtp
RCPT TO:<yyyyyyy@gmail.com>
250 2.1.5 OK uj7sm1724517pac.4 - gsmtp
DEBUG SMTP: Verified Addresses
DEBUG SMTP:   yyyyyyy@gmail.com
DATA
354  Go ahead uj7sm1724517pac.4 - gsmtp

Test mail Send Succesfully
.
250 2.0.0 OK 1416479656 uj7sm1724517pac.4 - gsmtp
QUIT
221 2.0.0 closing connection uj7sm1724517pac.4 - gsmtp

添加了多部分

的调试信息
DEBUG: getProvider() returning provider protocol=smtp; type=javax.mail.Provider$Type@17c7ee05; class=com.sun.mail.smtp.SMTPTransport; vendor=Oracle
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 587, isSSL false
220 mx.google.com ESMTP yl6sm1684572pbc.91 - gsmtp
DEBUG SMTP: connected to host "smtp.gmail.com", port: 587

EHLO localhost
250-mx.google.com at your service, [201.140.200.84]
250-SIZE 35882577
250-8BITMIME
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
STARTTLS
220 2.0.0 Ready to start TLS
EHLO localhost
250-mx.google.com at your service, [201.140.200.84]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER"
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
DEBUG SMTP: Attempt to authenticate using mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM 
DEBUG SMTP: AUTH LOGIN command trace suppressed
DEBUG SMTP: AUTH LOGIN succeeded
DEBUG SMTP: use8bit false
MAIL FROM:<xxxxxxxxx@gmail.com>
250 2.1.0 OK yl6sm1684572pbc.91 - gsmtp
RCPT TO:<yyyyyyy@gmail.com>
250 2.1.5 OK yl6sm1684572pbc.91 - gsmtp
DEBUG SMTP: Verified Addresses
DEBUG SMTP:   yyyyyyy@gmail.com
DATA
354  Go ahead yl6sm1684572pbc.91 - gsmtp

------=_Part_1_1348144858.1416480282126
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 7bit

Test mail Send Succesfully
------=_Part_1_1348144858.1416480282126--
.
250 2.0.0 OK 1416480266 yl6sm1684572pbc.91 - gsmtp
QUIT
221 2.0.0 closing connection yl6sm1684572pbc.91 - gsmtp

2 个答案:

答案 0 :(得分:1)

修改

以下链接描述了此问题的原因

http://yfrankfeng.blogspot.in/2012/07/java-mail-does-not-set-subject-problem.html

检查是否存在依赖关系org.apache.openejb

尝试设置主题的字符集

message.setSubject(subject,"utf-8");

答案 1 :(得分:0)

试试这个

Java文件

class MailClient
    extends Authenticator {

public static final int SHOW_MESSAGES = 1;
public static final int CLEAR_MESSAGES = 2;
public static final int SHOW_AND_CLEAR
        = SHOW_MESSAGES + CLEAR_MESSAGES;
public static String SMTP_AUTH_USER = "";
public static String SMTP_AUTH_PWD = "";

protected String from;
protected Session session;
protected PasswordAuthentication authentication;

public MailClient(String user, String pass, String host, String port) {
    this(user, pass, host, port, false);
}

public MailClient(String user, String pass, String host, String port, boolean debug) {
    from = user;//user + '@' + host;
    SMTP_AUTH_USER = user;
    SMTP_AUTH_PWD = pass;
    // authentication = new PasswordAuthentication(user, pass);
    Properties props = new Properties();
    props.put("mail.user", user);
    props.put("mail.host", host);
    props.put("mail.port", port);
    props.put("mail.smtp.port", port);
    props.put("mail.smtp.starttls.enable", "true");//
    props.put("mail.debug", debug ? "true" : "false");
    props.put("mail.store.protocol", "pop3");
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.auth", "true");

    //props.put("mail.smtp.starttls.enable","true" );   
    // props.put("mail.smtp.socketFactory.port", port);
    //  props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
    Authenticator auth = new SMTPAuthenticator();

    session = Session.getInstance(props, auth);
    //  System.out.println("mail session created");
}
@Override
public PasswordAuthentication getPasswordAuthentication() {
    return authentication;
}

public void sendMessage(
        String to, String subject, String content, String from)
        throws Exception {
    //InternetAddress[] replyToAddress = new InternetAddress[1];
    //replyToAddress[0] = new InternetAddress(reply);

    //System.out.println("SENDING message from " + from + " to " + to);
    //System.out.println();

    MimeMessage msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(from, "test"));

    msg.addRecipients(Message.RecipientType.TO, to);

    //msg.setReplyTo(replyToAddress);
    msg.setSubject(subject);

    msg.setText(content);

    msg.setContent(content, "text/html");

    Transport.send(msg);

   // System.out.println("Mail sent");
}
private class SMTPAuthenticator extends javax.mail.Authenticator {
    @Override
    public PasswordAuthentication getPasswordAuthentication() {
        String username = SMTP_AUTH_USER;
        String password = SMTP_AUTH_PWD;
        return new PasswordAuthentication(username, password);
    }
} } public class Mail {
static MailClient client;
public static boolean SendGMail(final String username, final String password, String host, String port, String recipientEmail, String subject, String message) throws AddressException, MessagingException {
    boolean status = false;
    client = new MailClient(username, password, host, port);
    try {          
        client.sendMessage(recipientEmail, subject, message, username);
        status = true;
    } catch (Exception ex) {
        ex.printStackTrace();
        Logger.getLogger(Mail.class.getName()).log(Level.SEVERE, null, ex);
    }
    return status;
} }

通话功能

Mail.SendGMail(appMail, appMailPwd, mailHost, mailPort, mailid, mailSubject, message);