异常SSLException在使用JavaMail API [英] SSLException in using JavaMail API

查看:206
本文介绍了异常SSLException在使用JavaMail API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我利用Java邮件API来开发一个应用程序来发送邮件。我可以成功地发送邮件,如果我是雅虎或Gmail使用的邮件服务器托管。然而,当我试图用我自己的邮件服务器,我无法发送邮件,是什么导致故障的可能原因?当我在设备执行我的应用程序,它会显示电子邮件未发送,所以没有异常发生。请问我怎样才能改变我的计划,所以我可以我的应用程序成功地连接到我的SMTP服务器,或者我怎样才能获得更多的信息,因此显示我可以理解为什么连接失败。

下面是我的程序:
Sender.java

 公共类发件人扩展活动{    按钮发送;
    TextView的文本;    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_sender);        发送=(按钮)findViewById(R.id.mail);
        文字=(TextView的)findViewById(R.id.textView1);        StrictMode.ThreadPolicy政策=新StrictMode.ThreadPolicy.Builder()
        .permitAll()建立()。
        StrictMode.setThreadPolicy(政策);        Send.setOnClickListener(新View.OnClickListener(){            @覆盖
            公共无效的onClick(视图v){
                // TODO自动生成方法存根
                新的SendMail()的execute()。
            }
        });    }    私有类的SendMail扩展的AsyncTask<弦乐,太虚,整数GT;
    {
        ProgressDialog PD = NULL;
        字符串错误= NULL;
        整数结果;        @覆盖
        在preExecute保护无效(){
            // TODO自动生成方法存根
            super.on preExecute();
            PD =新ProgressDialog(Sender.this);
            pd.setTitle(发送邮件);
            pd.setMessage(请稍候...);
            pd.setCancelable(假);
            pd.show();
        }        @覆盖
        保护整数doInBackground(字符串... PARAMS){
            // TODO自动生成方法存根            MailSender发件人=新MailSender(me@mysmtp.com,密码);            sender.setTo(新的String [] {you@mysmtp.com,me@gmail.com});
            sender.setFrom(me@mysmtp.com);
            sender.setSubject(测试邮件);
            sender.setBody(这是邮件正文);
            尝试{
                如果(sender.send()){
                    的System.out.println(消息派);
                    返回1;
                }其他{
                    返回2;
                }
            }赶上(例外五){
             错误= e.getMessage();
             Log.e(的SendMail,e.getMessage(),E);
            }
            返回3;
        }        保护无效onPostExecute(整数结果){
            pd.dismiss();
            如果(错误!= NULL){
                text.setText(错误);
            }
            如果(结果== 1){
                Toast.makeText(Sender.this,
                    电子邮件发送成功,Toast.LENGTH_LONG)
                    。显示();
            }否则如果(结果== 2){
                Toast.makeText(Sender.this,
                    电子邮件未发送,Toast.LENGTH_LONG).show();
            }否则如果(结果== 3){
                Toast.makeText(Sender.this,
                    有发送电子邮件的一个问题。
                    Toast.LENGTH_LONG).show();
            }
        }
    }
}

MailSender.java

 公共类MailSender扩展验证器{
    私人字符串用户;
    私人字符串密码;    私有String []来;
    私人字符串;    私人字符串口;
    私人字符串运动;    私人字符串主机;    私人字符串主体;
    私人字符串的身体;    私人布尔权威性;
    私人布尔调试的;    私人多部分多;    公共MailSender(){
        主机=web.mysmtp.com;
        端口=25;
        运动=25;        用户=;
        密码=;
        从=;
        主题=;
        体=;        可调试=假;
        AUTH = TRUE;        多=新MimeMultipart的();        //也有一些是错误的MAILCAP,JavaMail的找不到多部分/混合部分的处理程序,所以这一点需要添加。
        支持MailcapCommandMap MC =(支持MailcapCommandMap)CommandMap.getDefaultCommandMap();
        mc.addMailcap(text / html的;;的X Java的内容处理器= com.sun.mail.handlers.text_html);
        mc.addMailcap(text / plain的;;的X Java的内容处理器= com.sun.mail.handlers.text_plain);
        mc.addMailcap(多重/ * ;;的X Java的内容处理器= com.sun.mail.handlers.multipart_mixed);
        mc.addMailcap(信息/ RFC822 ;;的X Java的内容处理器= com.sun.mail.handlers.message_rfc822);
        CommandMap.setDefaultCommandMap(MC);
    }    公共MailSender(用户字符串,字符串密码){
        本();
        this.user =用户;
        this.password =密码;
    }    公共布尔的send()抛出异常{
        属性道具= setProperties();        尝试{
            会话的会话= Session.getInstance(道具,这一点);
            session.setDebug(真);            的MimeMessage味精=新的MimeMessage(会话);            msg.setFrom(新网际地址(从));            网际地址[] = addressTo新的网际地址[to.length]
            的for(int i = 0; I< to.length;我++){
                addressTo [I] =新的网际地址(在[I]);
            }            msg.setRecipients(MimeMessage.RecipientType.TO,addressTo);
            msg.setSubject(一级学科);
            msg.setSentDate(新的Date());            BodyPart的messageBodyPart =新MimeBodyPart();
            messageBodyPart.setText(体);
            multi.addBodyPart(messageBodyPart);            msg.setContent(多);            交通运输= session.getTransport(SMTPS);
            transport.connect(主机,25,用户,密码);
            transport.sendMessage(味精,msg.getAllRecipients());
            transport.close();
            返回true;
        }赶上(例外五){
            e.printStackTrace();
            返回false;
        }
    }    公共无效addAttachment(字符串文件名)抛出异常{
        BodyPart的messageBodyPart =新MimeBodyPart();
        数据源源=新FileDataSource(文件名);
        messageBodyPart.setDataHandler(新的DataHandler(源));
        messageBodyPart.setFileName(文件名);        multi.addBodyPart(messageBodyPart);
    }    @覆盖
      公众的PasswordAut​​hentication的getPasswordAut​​hentication(){
        返回新的PasswordAut​​hentication(用户名,密码);
      }    私人性质setProperties(){
        属性道具=新特性();        props.put(mail.smtp.host,主机);        如果(可调试){
            props.put(mail.debug为真);
        }        如果(AUTH){
            props.put(mail.smtp.auth,真);
        }        props.put(mail.smtp.port,口);
        props.put(mail.smtp.socketFactory.port,体育);
        props.put(mail.smtp.socketFactory.class,javax.net.ssl​​.SSLSocketFactory);
        props.put(mail.smtp.socketFactory.fallback,假);        返回道具;
    }    公共无效setTo(字符串[]的toAddress){
        this.to =的toAddress;
    }    公共无效setFrom(字符串FROMADDRESS){
        this.from = FROMADDRESS;
    }    公共无效SETSUBJECT(字符串主题){
        this.subject =主体;
    }    公共无效setBody(字符串体){
        this.body =身体;
    }
}

在错误日志中的错误消息:

  11月8日至15日:21:37.284:W / System.err的(2553):javax.net.ssl​​.SSLHandshakeException:javax.net.ssl​​.SSLProtocolException:SSL握手中止: SSL = 0x5c075548:失败的SSL库,通常一个协议错误
11月8日至15日:21:37.291:W / System.err的(2553):javax.net.ssl​​.SSLHandshakeException:产生的原因javax.net.ssl​​.SSLProtocolException:SSL握手中止:SSL = 0x5c075548:失败的SSL库,通常一个协议错误
11月8日至15日:21:37.299:W / System.err的(2553):javax.net.ssl​​.SSLProtocolException:致SSL握手中止:SSL = 0x5c075548:失败的SSL库,通常一个协议错误


解决方案

您正在连接到端口25和使用SSL。端口25是非SSL(纯文本)端口。假设你的服务器设置为SSL,使用不要求你指定端口号,并让JavaMail的使用默认端口connect方法。

I am making use of Java Mail API to develop an app to send mail. I can successfully send the mail if I use the mail server hosting by yahoo or gmail. However, when I try to use my own mail server, I am fail to send the mail, what are the possible reasons causing the failure? When I execute my app in my device, it displays "Email was not sent", so no exception occurs. May I ask how can I change my program so I can successfully connect my app to my smtp server, or how can I get more information to display therefore I can understand why the connection has failed.

Here is my program: Sender.java

public class Sender extends Activity {

    Button Send;
    TextView text;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sender);

        Send = (Button) findViewById(R.id.mail);
        text = (TextView) findViewById(R.id.textView1);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
        .permitAll().build();
        StrictMode.setThreadPolicy(policy); 

        Send.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new SendMail().execute();
            }
        });

    }

    private class SendMail extends AsyncTask<String, Void, Integer> 
    { 
        ProgressDialog pd = null;
        String error = null;
        Integer result;

        @Override 
        protected void onPreExecute() { 
            // TODO Auto-generated method stub 
            super.onPreExecute(); 
            pd = new ProgressDialog(Sender.this); 
            pd.setTitle("Sending Mail"); 
            pd.setMessage("Please wait..."); 
            pd.setCancelable(false); 
            pd.show(); 
        } 

        @Override  
        protected Integer doInBackground(String... params) {  
            // TODO Auto-generated method stub  

            MailSender sender = new MailSender("me@mysmtp.com", "password");  

            sender.setTo(new String[]{"you@mysmtp.com", "me@gmail.com"}); 
            sender.setFrom("me@mysmtp.com"); 
            sender.setSubject("Test mail"); 
            sender.setBody("This is the mail body"); 
            try { 
                if(sender.send()) { 
                    System.out.println("Message sent"); 
                    return 1; 
                } else {
                    return 2; 
                } 
            } catch (Exception e) {    
             error = e.getMessage(); 
             Log.e("SendMail", e.getMessage(), e);     
            } 
            return 3;  
        }  

        protected void onPostExecute(Integer result) { 
            pd.dismiss(); 
            if(error!=null) { 
                text.setText(error); 
            } 
            if(result==1) { 
                Toast.makeText(Sender.this, 
                    "Email was sent successfully.", Toast.LENGTH_LONG) 
                    .show(); 
            } else if(result==2) { 
                Toast.makeText(Sender.this, 
                    "Email was not sent.", Toast.LENGTH_LONG).show(); 
            } else if(result==3) { 
                Toast.makeText(Sender.this, 
                    "There was a problem sending the email.", 
                    Toast.LENGTH_LONG).show(); 
            } 
        } 
    }  
}

MailSender.java

public class MailSender extends Authenticator { 
    private String user; 
    private String password; 

    private String [] to; 
    private String from; 

    private String port; 
    private String sport; 

    private String host; 

    private String subject; 
    private String body; 

    private boolean auth; 
    private boolean debuggable; 

    private Multipart multi; 

    public MailSender(){ 
        host = "web.mysmtp.com"; 
        port = "25"; 
        sport = "25"; 

        user = ""; 
        password = ""; 
        from = ""; 
        subject = ""; 
        body = ""; 

        debuggable = false; 
        auth = true; 

        multi = 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 mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();  
        mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");  
        mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");  
        mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); 
        mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");  
        CommandMap.setDefaultCommandMap(mc);  
    } 

    public MailSender(String user, String password){ 
        this();       
        this.user = user; 
        this.password = password;    
    } 

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

        try{ 
            Session session = Session.getInstance(props, this); 
            session.setDebug(true); 

            MimeMessage msg = new MimeMessage(session); 

            msg.setFrom(new InternetAddress(from)); 

            InternetAddress[] addressTo = new InternetAddress[to.length]; 
            for(int i=0; i<to.length; i++){ 
                addressTo[i] = new InternetAddress(to[i]); 
            } 

            msg.setRecipients(MimeMessage.RecipientType.TO, addressTo); 
            msg.setSubject(subject); 
            msg.setSentDate(new Date()); 

            BodyPart messageBodyPart = new MimeBodyPart(); 
            messageBodyPart.setText(body); 
            multi.addBodyPart(messageBodyPart); 

            msg.setContent(multi); 

            Transport transport = session.getTransport("smtps"); 
            transport.connect(host, 25, user, password); 
            transport.sendMessage(msg, msg.getAllRecipients()); 
            transport.close(); 
            return true; 
        } catch (Exception e) { 
            e.printStackTrace(); 
            return false; 
        } 
    } 

    public void addAttachment(String filename) throws Exception { 
        BodyPart messageBodyPart = new MimeBodyPart(); 
        DataSource source = new FileDataSource(filename); 
        messageBodyPart.setDataHandler(new DataHandler(source)); 
        messageBodyPart.setFileName(filename); 

        multi.addBodyPart(messageBodyPart); 
    } 

    @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", sport); 
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); 
        props.put("mail.smtp.socketFactory.fallback", "false"); 

        return props; 
    } 

    public void setTo(String[] toAddress) { 
        this.to = toAddress; 
    } 

    public void setFrom(String fromAddress) { 
        this.from = fromAddress; 
    } 

    public void setSubject(String subject) { 
        this.subject = subject; 
    } 

    public void setBody(String body) {  
        this.body = body;  
    } 
}

Error messages in error log:

08-15 11:21:37.284: W/System.err(2553):     javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x5c075548: Failure in SSL library, usually a protocol error
08-15 11:21:37.291: W/System.err(2553): Caused by: javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x5c075548: Failure in SSL library, usually a protocol error
08-15 11:21:37.299: W/System.err(2553): Caused by: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x5c075548: Failure in SSL library, usually a protocol error

解决方案

You're connecting to port 25 and using SSL. Port 25 is the non-SSL (plain text) port. Assuming your server is set up for SSL, use the connect method that doesn't require you to specify a port number and let JavaMail use the default port.

这篇关于异常SSLException在使用JavaMail API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆