当前位置: 首页 > 知识库问答 >
问题:

使用JavaMail API时的SSLException

杜弘伟
2023-03-14

我正在利用Java Mail API开发一个发送邮件的应用程序。如果我使用雅虎或gmail托管的邮件服务器,我可以成功地发送邮件。然而,当我尝试使用自己的邮件服务器时,我无法发送邮件,导致失败的可能原因是什么?当我在我的设备上执行我的应用程序时,它会显示“电子邮件未发送”,因此不会发生异常。我想问一下,如何更改程序,以便将我的应用程序成功连接到smtp服务器,或者如何获得更多信息以显示,从而了解连接失败的原因。

这是我的程序:发送者。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(); 
            } 
        } 
    }  
}

邮件发送者。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;  
    } 
}

错误日志中的错误消息:

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

共有3个答案

颛孙智勇
2023-03-14

您可能会收到该错误,因为您没有在服务器端创建签名证书。如果您确实设置了SSL验证,则可能是您没有正确设置,或者您正在连接到一台证书尚未添加到信任库的服务器。

这篇帖子(我如何通过Android访问SSL连接?)有一个关于如何初始化密钥库和信任库的代码示例

蒋浩
2023-03-14

我会首先检查SMTP服务器的SSL配置。如果您的类与外部服务一起工作,那么它就是服务器的安全配置。

施令秋
2023-03-14

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

 类似资料:
  • 我有一个IMAP服务器主机名:xyz.com.我的SMTP主机名是:comcast.net. 现在,当我通过Outlook发送电子邮件时,它会自动将我的ID[发件人ID]显示为:myusername@xyz.com而不是myusername@comcast.net. 我想用JavaMail API实现同样的目标。 当我使用JavaMail API时,它将发送者显示为myusername@comca

  • 我有两个应用程序:App1和App2 在App1中指定的权限如下所示 java.lang.SecurityException:权限拒绝:从PID=5550,UID=10919读取com.commonname.providers.app1 uri内容://com.commonname.providers.app1.read_login_token或ranturiPermission()(位于Andr

  • 有没有办法在使用 jongo 查询 MongoDB 时添加 ?我发现这样的错误 - '排序超出了 104857600 字节的内存限制,但没有选择加入外部排序。正在中止操作。传递 allowDiskUse:true 可以选择加入,可以通过以下方式阻止,您的聚合看起来像 但据我所知,Jongo 中的类仅将管道应用于自身,然后您可以使用 方法执行。 是否有任何方法可以将该参数传递给mongo而不从Jon

  • 问题内容: 我在Web应用程序中使用Jersey 2.13检索数据异步。在某些情况下,请求需要一段时间(即执行复杂报告时,即EE)才能将响应返回给客户端。 当客户端不等待异步响应(离开页面,关闭浏览器等)时,将抛出ClientAbortException。此行为是预期的,但它使堆栈跟踪淹没了我的日志文件,因为在响应返回之前被取消的每个单个异步请求都会打印堆栈跟踪。 堆栈跟踪如下所示: 我也正在使用

  • 我刚开始使用线程,一调用wait方法就会得到一个IllegalMonitorStateException,有人能帮我吗