4

我一直在复制这段代码 http://www.tutorialspoint.com/java/java_sending_email.htm

我得到了错误

javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 465;
nested exception is:
java.net.SocketException: Connection reset
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1963)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
at javax.mail.Service.connect(Service.java:345)
at javax.mail.Service.connect(Service.java:226)
at javax.mail.Service.connect(Service.java:175)
at racetiming.MailSender.send(MailSender.java:68)

我正在查找的所有解决方案都使用身份验证来登录邮件服务器,但我试图在没有登录的情况下进行。这不可能吗?似乎教程正在尝试在没有凭据的情况下进行操作。

这是我的全部代码。

public class MailSender
{
public static void send(Racer r, String filename){
  // Recipient's email ID needs to be mentioned.
  String to = r.getEmail();

  // Sender's email ID needs to be mentioned
  String from = "donotreplyRFID@gmail.com";

  // Assuming you are sending email from localhost
  String host = "localhost";

  // Get system properties
  Properties properties = System.getProperties();

  // Setup mail server
  properties.setProperty("mail.smtp.host", host);
  properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

  // Get the default Session object.
  Session session = Session.getDefaultInstance(properties);

  try{
     // Create a default MimeMessage object.
     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("Report for " + r.getName());

     // Create the message part 
     BodyPart messageBodyPart = new MimeBodyPart();

     // Fill the message
     messageBodyPart.setText("See attachment");

     // Create a multipart message
     Multipart multipart = new MimeMultipart();

     // Set text message part
     multipart.addBodyPart(messageBodyPart);

     // Part two is attachment
     messageBodyPart = new MimeBodyPart();
     DataSource source = new FileDataSource(filename);
     messageBodyPart.setDataHandler(new DataHandler(source));
     messageBodyPart.setFileName(filename);
     multipart.addBodyPart(messageBodyPart);

     // Send the complete message parts
     message.setContent(multipart);

     // Send message
     Transport transport = session.getTransport("smtps");
     transport.connect();
     transport.sendMessage(message, message.getAllRecipients());
     System.out.println("Sent message successfully....");
  }catch (MessagingException mex) {
     mex.printStackTrace();
  }
   }
}
4

2 回答 2

5

这是可能的,但您需要自己在 DNS 中查找 MX 记录。您可以为此使用dnsjava-2.16.jar库。添加 dnsjava 和 javax.mail 库以构建路径以编译以下代码示例。尝试以这种方式发送邮件后检查您的垃圾邮件文件夹:因为没有 DKIM 签名,并且您用于发送电子邮件的 IP 地址不属于该主机允许的地址(“yourhost.org”),因此接收电子邮件服务器可能会将电子邮件放入垃圾邮件文件夹。

import com.sun.mail.smtp.SMTPSendFailedException;
import com.sun.mail.smtp.SMTPSenderFailedException;
import com.sun.mail.util.MailConnectException;
import org.xbill.DNS.*;

import javax.mail.Message;
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class SendEmail {
        String Subject = "Email subject!";
        Template template;
        Properties properties;
        String hostname = "yourhost.org"; // the host to send email from
        String to;
        String fromEmal;
        String fromName = "Your name";

        SendEmail(String from,String to){
            this.to = to;
            this.fromEmal = from;
            this.properties = new Properties();
            this.properties.put("mail.transport.protocol", "smtp");
            this.properties.put("mail.smtp.host", getMXRecordsForEmailAddress(to)); // SMTP Server
            this.properties.put("mail.smtp.port","25");
            this.properties.put("mail.smtp.localhost", hostname); // HELO host
            this.properties.put("mail.smtp.from",from);// SMTP MAIL FROM
            this.properties.put("mail.smtp.allow8bitmime","true");

           // this.properties.put("mail.smtp.localaddress","192.168.1.44"); // Connect from this IP
            sendMessage();
        }


        public void sendMessage() {

            try{

                Session session = Session.getInstance(this.properties);
                MimeMessage msg = new MimeMessage(session);

                msg.setFrom(new InternetAddress("\""+this.fromName+"\""+"<"+this.fromEmal+">"));
                msg.addRecipient(Message.RecipientType.TO,
                        new InternetAddress(this.to));

                msg.setSubject(this.Subject);

                msg.setContent("Email body <b>with HTML</b>","text/html; charset=utf-8");

                Transport.send(msg);
                System.out.println("Message sent OK");


            }catch (AddressException e){
                System.out.println("Bad address format: "+e.getRef());
            }catch (SMTPSenderFailedException e){
                System.out.println(e.getReturnCode() + ": We can't send emails from this address: " + e.getAddress());
            }catch (NoSuchProviderException e){
                System.out.println(e.getMessage()+": No such provider");
            }catch (SMTPSendFailedException e){
                System.out.print(e.getReturnCode() + ": " + e.getMessage());
            }catch (MailConnectException e){
                System.out.println("Can't connect to "+ e.getHost()+":"+e.getPort());
            }
            catch(MessagingException e){
                System.out.println("Unknown exception"+e);
            }catch (Exception e){
                System.out.println(e);
            }

        }


    public  String getMXRecordsForEmailAddress(String eMailAddress) {
        String returnValue = new String();

        try {
            String parts[] = eMailAddress.split("@");
            String hostName = parts[1];

            Record[] records = new Lookup(hostName, Type.MX).run();
            if (records == null) { throw new RuntimeException("No MX records found for domain " + hostName + "."); }

            if (records.length > 0){
                MXRecord mxr = (MXRecord) records[0];
                for (int i = 0; i< records.length; i++){
                    MXRecord tocompare = (MXRecord)records[i];
                    if (mxr.getPriority() > tocompare.getPriority())
                        mxr = tocompare;
                }
                returnValue = mxr.getTarget().toString();
            }

        } catch (TextParseException e) {
            return new String("NULL");

        }

        return returnValue;
    }

}
于 2014-04-06T11:38:27.927 回答
1

是否需要身份验证取决于您的服务器。某些 Intranet 邮件服务器可能不会。大多数互联网邮件服务器会,以防止垃圾邮件。

您还需要阅读有关常见错误的 JavaMail FAQ 条目。

于 2013-11-06T19:29:45.700 回答