无法从java程序身份验证发送邮件失败errorauthentication失败错误

时间:2013-12-06 02:32:52

标签: java

我无法发送邮件 - 该程序正在抛出身份验证错误

package com.gmc.registration.util;

import java.util.*;
import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class MailWithAttachement {

    private String sender;
    private String addressee;
    private String subject;
    private String nameOfAttachedFile;
    private String filePath;
    private String body;
    private String contentType;
    private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    private transient String SMTP_AUTH_USER = "";
    private transient String SMTP_AUTH_PWD  = "";

    public MailWithAttachement(final String sender, final String addressee, final String subject, final String nameOfAttachedFile, final String filePath, final String body, final String contentType) {
        this.sender = sender;
        this.addressee = addressee;
        this.subject = subject;
        this.nameOfAttachedFile = nameOfAttachedFile;
        this.filePath = filePath;
        this.body = body;
        this.contentType = contentType;
    }

    public int send() {
        int flag = 0;

        final ResourceBundle resource = ResourceBundle.getBundle("com.gmc.student.resourseprop.student");
        final Properties mailServerProperties = new Properties();
        mailServerProperties.put("mail.smtp.host", resource.getString("mail.smtp.host"));

        mailServerProperties.put("mail.smtp.port", resource.getString("mail.smtp.port"));
        mailServerProperties.put("mail.smtp.auth", resource.getString("mail.smtp.auth"));
        mailServerProperties.put("mail.smtp.sendpartial", resource.getString("mail.smtp.sendpartial"));

        final Authenticator auth = new SMTPAuthenticator(resource.getString("mail.smtp.username"), resource.getString("mail.smtp.password"));
    final Session session = Session.getDefaultInstance(mailServerProperties, auth);

//        final Session session = Session.getInstance(mailServerProperties);
//        final  Session session = Session.getDefaultInstance(mailServerProperties);
        final MimeMessage messageToSend = new MimeMessage(session);
        try {
            messageToSend.setFrom(new InternetAddress(this.sender));
            messageToSend.setRecipients(Message.RecipientType.TO, InternetAddress.parse(addressee));

            messageToSend.setSubject(this.subject);
            final BodyPart bodyText = new MimeBodyPart();
            bodyText.setContent(this.body, this.contentType);
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(bodyText);

            if (this.nameOfAttachedFile != null && this.filePath != null && !"".equals(this.nameOfAttachedFile) && !"".equals(this.filePath)) {
                addAttachments(multipart);
            }

            messageToSend.setContent(multipart);

            Transport.send(messageToSend);

            flag = 1;
        } catch (MessagingException exception) {

        } catch (Exception excp) {

        }
        return flag;
    }

    private void addAttachments(final Multipart multipart) {
        try {
            final BodyPart attachment = new MimeBodyPart();
            DataSource dataSource = new FileDataSource(this.filePath + this.nameOfAttachedFile);

            attachment.setDataHandler(new DataHandler(dataSource));
            attachment.setFileName(this.nameOfAttachedFile);
            multipart.addBodyPart(attachment);
        } catch (MessagingException excp) {

        }
    }

    public static boolean emailvalidation(final String email) {
        Pattern pattern = Pattern.compile(EMAIL_PATTERN);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }

    /**
     * SimpleAuthenticator is used to do simple authentication
     * when the SMTP server requires it.
     */
    private class SMTPAuthenticator extends javax.mail.Authenticator {

        private SMTPAuthenticator(final String username, final String password) {
            SMTP_AUTH_USER = username;
            SMTP_AUTH_PWD = password;
        }

        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(SMTP_AUTH_USER, SMTP_AUTH_PWD);
        }
    }

    public static void main(String[] args) {
        new MailWithAttachement("ash.k@test.com", "xxh.k@test.com", "sub", null, null, "<h1>This is a test</h1>"
           + "", "text/html").send();
    }
}

道具文件

mail.attachement.filepath=E:/test/attchedFiles/
mail.smtp.host=mail.test.com
mail.smtp.port=587
mail.smtp.username=ash.t
mail.smtp.password=123456
mail.smtp.auth=true
mail.smtp.sendpartial=true

1 个答案:

答案 0 :(得分:0)

由于你没有给出一个例外的详细信息,我发布了我在生产中使用的模块,它似乎与gmail帐户相当不错。

/**
 GmailSmtpSSL emailNotify = new GmailSmtpSSL(cred[ID], cred[PASS]);

 emailNotify.sendMailTo("self","Testing AlfaDX Gmail module", "Yes it works");

**/

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class GmailSmtpSSL {

    GmailSmtpSSL(String username,String password) {
        usern = username;
        pass  = password;

        setDebugMsg("Setting user name to : "+usern);
        setDebugMsg("Using given password : "+pass);

        props = new Properties();
        setDebugMsg("Setting smtp server: smtp.gmail.com");
        setDebugMsg("Using SSL at port 465 auth enabled");

        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.user", usern);

        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        //props.put("mail.smtp.debug", "true");

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

        SMTPAuthenticator auth = new SMTPAuthenticator();
        session = Session.getDefaultInstance(props, auth);
        session.setDebug(true);
        setDebugMsg("Session initialization complete");
    }

    public void destroy() {
        props.clear();
        props = null;
        usern = null;
        pass  = null;
        session = null;

    }

    public void sendMailTo(String to, String sub, String body)
                                                    throws MessagingException {

         Calendar currentDate = Calendar.getInstance();
         SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss a"); 
         String dateToday = formatter.format(currentDate.getTime()).toLowerCase();

         if (to.equals("self")) 
             to = usern;

         setDebugMsg("Composing message: To "+to);
         setDebugMsg("Composing message: Subject "+sub);

         try {
             Message message = new MimeMessage(session);
             message.setFrom(new InternetAddress(usern));
             message.setRecipients(Message.RecipientType.TO, 
                                                    InternetAddress.parse(to));
             message.setSubject("PinguBot: "+dateToday+" "+sub);
             message.setText(body);
             setDebugMsg("Attempting to send...");
             Transport transport = session.getTransport("smtps");

             transport.connect("smtp.gmail.com", 465, usern, pass);
             Transport.send(message);
             transport.close();
         }

         catch(MessagingException me) {
             setDebugMsg(me.toString());
             throw new MessagingException(me.toString());
         }
             setDebugMsg("Mail was send successfully");
    }


    public String getDebugMsg() {
        String msg = new String(debugMsg);
        debugMsg = " ";
        return msg;
    }
    private static void setDebugMsg(String msg) {
        debugMsg += msg + "\n";
        System.out.println(msg);
    }

    private static String debugMsg = "";
    private String usern; 
    private String pass;
    private Session session;
    private static Properties props;

    private class SMTPAuthenticator extends Authenticator
    {
        public PasswordAuthentication getPasswordAuthentication()
        {
            return new PasswordAuthentication(usern, pass);
        }
    }

}