在java eclipse中发送邮件不起作用

时间:2017-05-24 17:24:50

标签: java eclipse email

我正在尝试创建一个发送电子邮件的函数(在eclipse中的java用户密码重置类中)。这是在学校的电脑上。我不确定这是计算机或代码的问题。它可能是计算机,因为学校对它有很多限制。但是代码也使用端口25,它应该使用587,如输出中所示。我的代码如下。

package Jframet;

import java.io.*;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Properties;
import java.util.Random;

import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class serial implements java.io.Serializable
{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private String uc;
    private String pc;
    private String ec;

public serial()
{
    uc = "";
    pc = "";
    ec = "";
}
public serial(String u, String p, String e)
{
    uc = u;
    pc = p;
    ec = e;     
}



public boolean serialize(String s,serial e)
{
    boolean b = true;
    try {
        File f = new File(s+this.uc+".ser");
        String pathname = f.getPath();
         FileOutputStream fileOut = new FileOutputStream(pathname);
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(e);
         out.close();
         fileOut.close();
      }catch(IOException i) {
          i.printStackTrace();
         b = false;
      }
    return b;
}

public boolean deserial(String u,String p)
{
    boolean b = true;
    serial e;
    File test = new File("H:/classes/" + u + ".ser");
    if(!test.exists())
    {
        b = false;
        return b;
    }
    else
    {
        try {
            FileInputStream fileIn = new FileInputStream(test);
            ObjectInputStream in = new ObjectInputStream(fileIn);
            e = (serial) in.readObject();
            in.close();
            fileIn.close();

        } catch (IOException i) {
            e = null;
            i.printStackTrace();
            b = false;

        } catch (ClassNotFoundException c) {
            e = null;
            c.printStackTrace();
            b = false;

        }
        String s1 = u;
        String s2 = e.uc;
        if(s1.compareTo(s2) == 0)
        {
            try{
                if(!PasswordAuthentication.validatePassword(p,e.pc))
                {
                    b = false;
                }
                else{}
                }catch(NoSuchAlgorithmException i){  i.printStackTrace();
                b = false;}
                catch(InvalidKeySpecException i){  i.printStackTrace();
                b = false;}

        }
        else
        {
            b = false;
        }
    }

    return b;
}
public int emailtest(String u,String em)
{
    Random r = new Random();
    int b = r.nextInt(999999);
    serial e;
    File test = new File("H:/classes/" + u + ".ser");
    if(!test.exists())
    {
        b = 0;
        return b;
    }
    else
    {
        try {
            FileInputStream fileIn = new FileInputStream(test);
            ObjectInputStream in = new ObjectInputStream(fileIn);
            e = (serial) in.readObject();
            in.close();
            fileIn.close();

        } catch (IOException i) {
            e = null;
            i.printStackTrace();
            b = 0;

        } catch (ClassNotFoundException c) {
            e = null;
            c.printStackTrace();
            b = 0;

        }
        if(u.compareTo(e.uc) == 0 && em.compareTo(e.ec) == 0)
        {
              String to = em;
              String from = "168464@mcpsmd.net";
              String host = "smtp.mail.com";
              String port = "587";
              Properties properties = System.getProperties();
              properties.setProperty("mail.smtp.host", host);
              properties.put("mail.smtp.socketFactory.port", port);
              properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
              properties.put("mail.smtp.socketFactory.fallback", "false");
              Session session = Session.getInstance(properties, null);

              try {
                 MimeMessage message = new MimeMessage(session);
                 // Set From: header field of the header.
                 message.setFrom(new InternetAddress(from));
                 // Set To: header field of the header.
                 message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
                 // Set Subject: header field
                 message.setSubject("Password Reset");
                 // Now set the actual message
                 message.setText(Integer.toString(b));
                 // Send message
                 Transport.send(message);
                 System.out.println("Sent message successfully....");
              }catch (MessagingException mex) {
                 mex.printStackTrace();
              }
        }
        else
        {
            if(u.compareTo(e.uc) != 0)
            {
                b = -1;
            }
            else
            {
                b = 0;
            }
        }
    }

    return b;
}


}

我的输出是

    javax.mail.MessagingException: Could not connect to SMTP host: smtp.mail.com, port: 25;
  nested exception is:
    java.net.SocketException: Permission denied: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1972)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:642)
    at javax.mail.Service.connect(Service.java:295)
    at javax.mail.Service.connect(Service.java:176)
    at javax.mail.Service.connect(Service.java:125)
    at javax.mail.Transport.send0(Transport.java:194)
    at javax.mail.Transport.send(Transport.java:124)
    at Jframet.serial.emailtest(serial.java:165)
    at Jframet.loginpage$6.mouseClicked(loginpage.java:345)
    at java.awt.AWTEventMulticaster.mouseClicked(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$500(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: java.net.SocketException: Permission denied: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
    at sun.security.ssl.BaseSSLSocketImpl.connect(Unknown Source)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:319)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:207)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1938)
    ... 40 more

1 个答案:

答案 0 :(得分:0)

您需要添加PasswordAuthentication,例如: 更新

    String to = em;
    String from = "168464@mcpsmd.net";
    String host = "smtp.mail.com";
    String port = "587";
    String password = //Your email password
    Properties properties = System.getProperties();
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.port", "587");

    if (from.contains("hotmail")) {
        properties.put("mail.smtp.host", "smtp.live.com");

    } else if (from.contains("gmail")) {
        properties.put("mail.smtp.host", "smtp.gmail.com");

    } else if (from.contains("yahoo")) {
        properties.put("mail.smtp.host", "smtp.mail.yahoo.com");

    } else {
        System.out.println("Please use 'Yahoo, Gmail or Hotmail")
    }

    Session messageSession = Session.getDefaultInstance(properties, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {

            return new PasswordAuthentication(from, password);
        }
    });

    try {
        MimeMessage mimeMessage = new MimeMessage(messageSession);
        mimeMessage.setFrom(new InternetAddress(from));
        mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
        mimeMessage.setSubject(subject);
        mimeMessage.setText(message);

        Transport.send(mimeMessage);

    } catch (MessagingException e) {
        System.out.println(e.getMessage());
    }