Is it possible to send mail with Javamail without

2019-06-26 04:56发布

I've been copying this code http://www.tutorialspoint.com/java/java_sending_email.htm

and I get the error

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)

All the solutions I'm looking up are using authentication to log in to a mail server but I'm trying to do it without a login. Is this not possible? Seems like the tutorials are trying to do it without credentials.

Here's the entirety of my code.

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();
  }
   }
}

2条回答
女痞
2楼-- · 2019-06-26 05:22

It's up to your server whether it requires authentication or not. Some intranet mail servers might not. Most internet mail servers will, to prevent spamming.

You'll also want to read this JavaMail FAQ entry about common mistakes.

查看更多
SAY GOODBYE
3楼-- · 2019-06-26 05:29

It is possible, but you need to lookup yourself the MX records in DNS. You can use dnsjava-2.16.jar library for that. Add dnsjava and javax.mail libraries to build path to compile the following code sample. Check your spam folder after trying to deliver the message this way: because there is no DKIM signature, and the IP address you use to send the email does not belong to addresses allowed for this host ("yourhost.org"), the receiving email server will likely put the email into spam folder.

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;
    }

}
查看更多
登录 后发表回答