是否有可能用JavaMail发送邮件,而认证? [英] Is it possible to send mail with Javamail without authentication?

查看:414
本文介绍了是否有可能用JavaMail发送邮件,而认证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在复制此code
http://www.tutorialspoint.com/java/java_sending_email.htm

和我得到的错误

  javax.mail.MessagingException的:无法连接到SMTP主机:本地主机,端口:465;
嵌套的异常是:
产生java.net.SocketException:连接重置
在com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1963)
在com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
在javax.mail.Service.connect(Service.java:345)
在javax.mail.Service.connect(Service.java:226)
在javax.mail.Service.connect(Service.java:175)
在racetiming.MailSender.send(MailSender.java:68)

所有我找了解决方案采用身份验证来登录到邮件服务器,但我试图做到这一点无需登录。这是不可能的?好像教程正在尝试做没有凭据。

下面是我的code的全部内容。

 公共类MailSender
{
公共静态无效发送(赛车R,字符串文件名){
  //收件人的电子邮件ID需要被提及。
  字符串= r.getEmail();  //发件人的电子邮件ID需要指出
  从=donotreplyRFID@gmail.com字符串;  //假设你从本地主机发送电子邮件
  字符串主机=localhost的;  //获取系统属性
  属性属性= System.getProperties();  //设置邮件服务器
  properties.setProperty(mail.smtp.host,主机);
  properties.put(mail.smtp.socketFactory.class,javax.net.ssl​​.SSLSocketFactory);  //获取默认的Session对象。
  会话的会话=作为Session.getDefaultInstance(属性);  尝试{
     //创建一个默认的MimeMessage对象。
     的MimeMessage消息=新的MimeMessage(会话);     //设置发件人:报头的报头字段。
     message.setFrom(新网际地址(从));     //设置为:头的头字段。
     message.addRecipient(Message.RecipientType.TO,
                              新的网际地址(至));     //设置主题:头字段
     message.setSubject(报告为+ r.getName());     //创建消息部分
     BodyPart的messageBodyPart =新MimeBodyPart();     //填写消息
     messageBodyPart.setText(见附件);     //创建一个多部分消息
     多部分多部分=新MimeMultipart的();     //设置短信一部分
     multipart.addBodyPart(messageBodyPart);     //第二部分是附件
     messageBodyPart =新MimeBodyPart();
     数据源源=新FileDataSource(文件名);
     messageBodyPart.setDataHandler(新的DataHandler(源));
     messageBodyPart.setFileName(文件名);
     multipart.addBodyPart(messageBodyPart);     //发送完整的消息部分
     message.setContent(多部分);     // 发信息
     交通运输= session.getTransport(SMTPS);
     transport.connect();
     transport.sendMessage(消息,message.getAllRecipients());
     的System.out.println(发送成功的消息......);
  }赶上(MessagingException MEX){
     mex.printStackTrace();
  }
   }
}


解决方案

这是可能的,但你需要查找自己在DNS MX记录。您可以使用 dnsjava-2.16.jar 库这一点。添加dnsjava和javax.mail库来构建路径编译下面code样品。请检查您的垃圾邮件文件夹中试图传递这样的留言后:因为没有DKIM签名,以及IP地址用于发送邮件不属于允许该主机(yourhost.org地址),接收电子邮件服务器将有可能把电子邮件到垃圾邮件文件夹。

 进口com.sun.mail.smtp.SMTPSendFailedException;
进口com.sun.mail.smtp.SMTPSenderFailedException;
进口com.sun.mail.util.MailConnectException;
进口org.xbill.DNS *。进口javax.mail.Message;
导入javax.mail *。
进口javax.mail.internet.AddressException;
进口javax.mail.internet.InternetAddress;
进口的javax.mail.internet.MimeMessage;
进口java.util.Properties;公共类SendEmail {
        字符串主题=电子邮件主题!
        模板的模板;
        性能特性;
        字符串主机=yourhost.org; //主机发送电子邮件从
        字符串;
        串fromEmal;
        字符串FROMNAME =你的名字;        SendEmail(从,串来串){
            this.to =到;
            this.fromEmal =距离;
            this.properties =新特性();
            this.properties.put(mail.transport.protocol,SMTP);
            this.properties.put(mail.smtp.host,getMXRecordsForEmailAddress(到)); // SMTP服务器
            this.properties.put(mail.smtp.port,25);
            this.properties.put(mail.smtp.localhost,主机名); // HELO主机
            this.properties.put(mail.smtp.from,从); // SMTP MAIL FROM
            this.properties.put(mail.smtp.allow8bitmime,真);           // this.properties.put(mail.smtp.localaddress,192.168.1.44); //从这个IP连接
            发信息();
        }
        公共无效的sendMessage(){            尝试{                会话的会话= Session.getInstance(this.properties);
                的MimeMessage味精=新的MimeMessage(会话);                msg.setFrom(新网际地址(\\+ this.fromName +\\+&下;+ this.fromEmal +>中));
                msg.addRecipient(Message.RecipientType.TO,
                        新的网际地址(this.to));                msg.setSubject(this.Subject);                msg.setContent(电子邮件正文< B>在HTML< / B>中为text / html;字符集= UTF-8);                Transport.send(MSG);
                的System.out.println(消息发送OK);
            }赶上(是AddressException E){
                的System.out.println(坏地址格式为:+ e.getRef());
            }赶上(SMTPSenderFailedException E){
                的System.out.println(e.getReturn code()+:我们不能从这个地址发送电子邮件:+ e.getAddress());
            }赶上(NoSuchProviderException E){
                的System.out.println(e.getMessage()+:没有这样的提供者);
            }赶上(SMTPSendFailedException E){
                System.out.print(e.getReturn code()+:+ e.getMessage());
            }赶上(MailConnectException E){
                的System.out.println(无法连接到+ e.getHost()+:+ e.getPort());
            }
            赶上(MessagingException E){
                的System.out.println(未知异常+ E);
            }赶上(例外五){
                的System.out.println(E);
            }        }
    公共字符串getMXRecordsForEmailAddress(字符串EMAILADDRESS){
        字符串的returnValue =新的String();        尝试{
            串件[] = eMailAddress.split(@);
            字符串主机名=零件[1];            实录[] =记录查找新(主机名,Type.MX).RUN();
            如果(记录== NULL){抛出新的RuntimeException(+主机+未找到域名的MX记录,); }            如果(records.length大于0){
                MXRecord MXR =(MXRecord)记录[0];
                的for(int i = 0; I< records.length;我++){
                    MXRecord tocompare =(MXRecord)记录[I]
                    如果(mxr.getPriority()> tocompare.getPriority())
                        MXR = tocompare;
                }
                。=的returnValue mxr.getTarget()的toString();
            }        }赶上(TextParseException E){
            返回新的String(NULL);        }        返回的returnValue;
    }}

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

解决方案

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

}

这篇关于是否有可能用JavaMail发送邮件,而认证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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