【问题标题】:Send Mail using JAVA使用 JAVA 发送邮件
【发布时间】:2012-03-27 14:22:41
【问题描述】:

你好我想用java发送一个简单的邮件。所以我下载了mail.jar和activation.jar文件,我写了一个简单的程序来发送它。

我的简单邮件程序编译成功.. 但是当我运行它时显示以下错误。

javax.mail.MessagingException:无法连接到 SMTP 主机:localhost,端口:25; 嵌套异常是: java.net.ConnectException:连接被拒绝:连接

我的疑问是如何找到我的 PC 的 SMTP 服务器名称?我在网站上搜索但没有得到任何清楚的东西..

请让我朝着正确的方向前进……

关于

泽维尔 KCB

【问题讨论】:

标签: java smtp jakarta-mail


【解决方案1】:

如果您想连接到 localhost,您需要在您的 PC 或服务器上安装并运行 SMTP 服务器。 有很多适用于 Windows 和 Linux 的免费软件。

【讨论】:

  • -1:TS需要配置JavaMail使用他的ISP的SMTP服务器,而不是安装本地的SMTP服务器
  • 如果他尝试连接到 localhost:25,他显然不想从他的 ISP 发送电子邮件,而是从他的服务器或其他地方发送电子邮件。所以你的 -1 对我来说有点随机。
  • 如果你没有正确配置 JavaMail(如:不要设置服务器)那么它默认为 localhost
【解决方案2】:

你的电脑不必使用 SMTP 服务器名称,你必须使用外部电子邮件服务器,例如 gmail、yahoo 等。你可以在你的电脑上设置邮件服务器,但它不在题。在您的情况下,您必须在免费邮件系统中注册新电子邮件,并使用它的 smtp 服务器和端口。 您可以通过 Google 搜索更多关于 JavaMail API 示例的信息:cafeaulaitvipan

【讨论】:

    【解决方案3】:

    假设您使用 gmail 发送电子邮件。详细代码如下:

    package ripon.java.mail;
    import javax.mail.*;
    import javax.mail.internet.*;
    import java.util.*;
    
    public class SendFromGmail {
        public static void main(String args[]){
            try{
                String host = "smtp.gmail.com";
                String from = "ripontest@gmail.com";
                String pass = "mypassword123";
                Properties props = System.getProperties();
                props.put("mail.smtp.starttls.enable", "true");
                props.put("mail.smtp.host", host);
                props.put("mail.smtp.user", from);
                props.put("mail.smtp.password", pass);
                props.put("mail.smtp.port", "587");
                props.put("mail.smtp.auth", "true");
    
                String[] to = {"riponalwasim@gmail.com"};
    
                Session session = Session.getDefaultInstance(props, null);
                MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(from));
                InternetAddress[] toAddress = new InternetAddress[to.length];
    
                // To get the array of addresses
                for( int i=0; i < to.length; i++ ) { // changed from a while loop
                    toAddress[i] = new InternetAddress(to[i]);
                }
                System.out.println(Message.RecipientType.TO);
    
                for( int i=0; i < toAddress.length; i++) { // changed from a while loop
                    message.addRecipient(Message.RecipientType.TO, toAddress[i]);
                }
                message.setSubject("sending in a group");
                message.setText("Welcome to JavaMail");
                Transport transport = session.getTransport("smtp");
                transport.connect(host, from, pass);
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();
            }
            catch(Exception e){
                e.getMessage();
            }
        }
    }
    

    【讨论】:

      【解决方案4】:

      您首先需要有一个电子邮件服务器。 所以请使用http://www.hmailserver.com/ 之类的,这是免费的。 请注意 Auto-Ban 选项,该选项可以关闭,否则会毁了你的一天。

      安装和设置,非常简单。

      完成后,您可以编写您的电子邮件客户端应用程序。

      检查这个:http://www.xmarks.com/site/www.digilife.be/quickreferences/PT/Fundamentals%2520of%2520the%2520JavaMail%2520API.pdf

      它是 PDF 格式的旧“JavaMail API 基础知识”网站,几乎是最好的来源(不知道为什么它不再在 oracle.com 上在线)。

      并在所有事项中参考这一点。这是一个非常好的教程,将指导您完成整个过程。寻找东西时的好参考:

      http://de.scribd.com/doc/11385837/All-About-Java-Mail

      不要使用一些 GMail 帐户左右进行开发 - 他们的服务器不会合作,因为你正在制造很多麻烦(连接太多,不断被禁止导致错误登录等) .

      【讨论】:

        【解决方案5】:

        这是 Tomcat 7 上的完整简短 program,它使用 SMTP 服务器作为服务(在本例中为 SendGrid)。我用它来发送电子邮件以恢复用户密码。

        您可以同时运行它,在本地启用免费的 SendGrid 服务,或者只是将其立即部署到开发该软件的特定 PaaS 上。

        【讨论】:

          【解决方案6】:

          这是您在执行电子邮件程序时可能遇到的第一个错误,如果没有正确纠正,可能会出现各种其他错误。

          这个问题和其他此类问题的可能解决方案,以及我用于使用公司邮箱发送电子邮件的代码:

          • 1) 正如许多其他成员已经提到的那样,正确的主机详细信息。 25 默认端口,如果不一样,请更改。
          • 2) 检查您访问的服务器是否要求进行身份验证或 不是。更多关于这在代码中。
          • 3) 一定要在 属性以了解您的代码和 邮件服务器。更多信息请参见代码。

          我的代码:

          package com.datereminder.service;
          
          import java.util.Properties;
          import javax.mail.Message;
          import javax.mail.MessagingException;
          import javax.mail.PasswordAuthentication;
          import javax.mail.Session;
          import javax.mail.Transport;
          import javax.mail.internet.InternetAddress;
          import javax.mail.internet.MimeMessage;
          
          public class ReminderDaemonService2 {
          
              /**
               * @param args
               */
              public static void main(String[] args) {
                  Properties props = new Properties();
                  props.put("mail.smtp.host", "mail.mycompany123.com");
          // this mandates authentication at the mailserver
                  props.put("mail.smtp.auth", "true");
          // this is for printing debugs
          
                  props.put("mail.debug", "true");
          
          
                  Session session = Session.getDefaultInstance(props,
                      new javax.mail.Authenticator() {
                          protected PasswordAuthentication getPasswordAuthentication() {
                              return new PasswordAuthentication("sadique.khan@mycompany123.com","xxxxxxxxxxx");
                          }
                      });
          
                  try {
          
                      Message message = new MimeMessage(session);
                      message.setFrom(new InternetAddress("sadique.khan@mycompany123.com"));
                      message.setRecipients(Message.RecipientType.TO,
                              InternetAddress.parse("my.bestfriend@mycompany123.com"));
                      message.setSubject("Testing Subject");
                      message.setText("Dear Friend," +
                              "\n\n This is a Test mail!");
          
                      Transport.send(message);
          
          
          
                  } catch (MessagingException e) {
                      throw new RuntimeException(e);
                  }
              }
          }
          

          【讨论】:

            【解决方案7】:

            通过本地 SMTP 发送邮件

            你好,同性恋! 如果您的应用程序在具有自己的 SMTP 服务器的服务器上执行(例如许多 UNIX 发行版,包括那些),Y 可以检查它:

            $ echo 'anytext' | mail -s 'mailSubject' recepient@example.com
            

            Y可以通过它发送消息:

            import java.io.IOException;
            import java.util.Date;
            import java.util.Properties;
            
            import javax.mail.*;
            import javax.mail.internet.*;
            
            public class MailSender {
            void systemSender(InternetAddress recepients, String subject, String body) throws IOException, AddressException, MessagingException {
            
                    Properties properties = new Properties();
                    Session session = Session.getDefaultInstance(properties , null);
            
                    Message msg = new MimeMessage(session);
                    msg.setFrom(new InternetAddress("do_not_reply@example.com", "NoReply"));
                    msg.addRecipient(Message.RecipientType.TO, recepients);
                    msg.setSubject(subject);
                    msg.setText(body);
                    Transport.send(msg);
                    System.out.println("Email sent successfully...");
                }
            }
            

            【讨论】:

              【解决方案8】:
              import java.util.Properties;
              
              import javax.activation.DataHandler;
              import javax.activation.DataSource;
              import javax.activation.FileDataSource;
              import javax.mail.Message;
              import javax.mail.MessagingException;
              import javax.mail.Multipart;
              import javax.mail.Session;
              import javax.mail.Transport;
              import javax.mail.internet.AddressException;
              import javax.mail.internet.InternetAddress;
              import javax.mail.internet.MimeBodyPart;
              import javax.mail.internet.MimeMessage;
              import javax.mail.internet.MimeMultipart;
              
              
              public class MailSender {
              
                  public final String mailServerAddress;
                  public final int mailServerPort;
                  public final String senderAddress;
              
                  public MailSender(String mailServerAddress, int mailServerPort, String senderAddress) {
                      this.senderAddress = senderAddress;
                      this.mailServerAddress = mailServerAddress;
                      this.mailServerPort = mailServerPort;
                  }
              
                  public void sendMail(String to[], String cc[], String bcc[], String replyTo[], String subject, String body, String[] attachments) {
              
                      if (to == null || to.length <= 0) {
                          System.out.println("sendMail To address is NULL for email");
                      }
              
                      if (subject == null || subject.length() <= 0) {
                          System.out.println("sendMail Subject is NULL for email");
                      }
              
                      if (body == null || body.length() <= 0) {
                          System.out.println("sendMail Body is NULL for email");
                      }
              
                      Properties props = new Properties();
                      // Specify the desired SMTP server and port
                      props.put("mail.smtp.host", mailServerAddress);
                      props.put("mail.smtp.port", Integer.toString(mailServerPort));
                      props.put("mail.smtp.auth", "true");
              
                      //TODO can we create session only once, with some session validation
                      Session session = Session.getInstance(props, null);
              
                      // create a new MimeMessage object (using the Session created above)
                      Message message = new MimeMessage(session);
                      StringBuilder addresses = new StringBuilder();
                      addresses.append("FROM:").append(senderAddress);
                      try {
                          message.setFrom(new InternetAddress(senderAddress));
              
                          // TO:
                          InternetAddress[] toAddresses = new InternetAddress[to.length];
                          addresses.append(" TO:");
                          for (int i = 0; i < to.length; i++) {
                              toAddresses[i] = new InternetAddress(to[i]);
                              addresses.append(to[i] + ";");
                          }
                          message.setRecipients(Message.RecipientType.TO, toAddresses);
              
                          // CC:
                          if (cc != null && cc.length > 0) {
                              InternetAddress[] ccAddresses = new InternetAddress[cc.length];
                              addresses.append(" CC:");
                              for (int i = 0; i < cc.length; i++) {
                                  ccAddresses[i] = new InternetAddress(cc[i]);
                                  addresses.append(cc[i] + ";");
                              }
                              message.setRecipients(Message.RecipientType.CC, ccAddresses);
                          }
              
                          // BCC:
                          if (bcc != null && bcc.length > 0) {
                              InternetAddress[] bccAddresses = new InternetAddress[bcc.length];
                              addresses.append(" BCC:");
                              for (int i = 0; i < bcc.length; i++) {
                                  bccAddresses[i] = new InternetAddress(bcc[i]);
                                  addresses.append(bcc[i] + ";");
                              }
                              message.setRecipients(Message.RecipientType.BCC, bccAddresses);
                          }
              
                          // ReplyTo:
                          if (replyTo != null && replyTo.length > 0) {
                              InternetAddress[] replyToAddresses = new InternetAddress[replyTo.length];
                              addresses.append(" REPLYTO:");
                              for (int i = 0; i < replyTo.length; i++) {
                                  replyToAddresses[i] = new InternetAddress(replyTo[i]);
                                  addresses.append(replyTo[i] + ";");
                              }
                              message.setReplyTo(replyToAddresses);
                          }
              
                          // Subject:
                          message.setSubject(subject);
                          addresses.append(" SUBJECT:").append(subject);
              
                          // Body:
                          Multipart multipart = new MimeMultipart();
              
                          MimeBodyPart mimeBody = new MimeBodyPart();
                          mimeBody.setText(body);
                          multipart.addBodyPart(mimeBody);
              
                          // Attachments:
                          if (attachments != null && attachments.length > 0) {
                              for (String attachment : attachments) {
                                  MimeBodyPart mimeAttachment = new MimeBodyPart();
                                  DataSource source = new FileDataSource(attachment);
                                  mimeAttachment.setDataHandler(new DataHandler(source));
                                  mimeAttachment.setFileName(attachment);
                                  multipart.addBodyPart(mimeAttachment);
                              }
                          }
              
                          message.setContent(multipart);
              
                          // Send
                          //Transport.send(message);
                          String username = "amol@postmaster";
                          String password = "amol";
                          Transport tr = session.getTransport("smtp");
                          tr.connect(mailServerAddress, username, password);
                          message.saveChanges();      // don't forget this
                          tr.sendMessage(message, message.getAllRecipients());
                          tr.close();
                          System.out.println("sendmail success " + addresses);
                      } catch (AddressException e) {
                          System.out.println("sendMail failed " + addresses);
                          e.printStackTrace();
                      } catch (MessagingException e) {
                          System.out.println("sendMail failed " + addresses);
                          e.printStackTrace();
                      }
                  }
              
                  public static void main(String s[]) {
                      if (s.length < 3) {
                          System.out.println("Usage: MailSender RelayAddress SendersAddress ToAddress [ AttachmentFileName ]");
                          System.exit(-1);
                      }
                      int k = 0;
                      String relay = s[k++];
                      String sender = s[k++];
                      String[] toAddresses = new String[] {s[k++]};
                      String[] attachmentFileName = new String[0];
              
                      if (s.length == 4) {
                          attachmentFileName = new String[] {s[k++]};
                      }
              
                      MailSender mailSender = new MailSender(relay, 25, sender);
              
                      String[] mailTo = toAddresses;
                      String[] mailCC = new String[] {};
                      String[] mailBCC = new String[] {};
                      String[] replyTo = new String[] {};
              
                      String mailSubject = "Test Mail";
                      String mailBody = "Mail sent using test utility";
              
                      mailSender.sendMail(mailTo, mailCC, mailBCC, replyTo, mailSubject, mailBody, attachmentFileName);
              
                  }
              
              }
              

              【讨论】:

              • 您可能想添加一些解释,而不仅仅是扔一些代码。
              【解决方案9】:

              使用您的 Java 应用程序发送电子邮件非常简单,但首先您应该在您的机器上安装 JavaMail API 和 Java 激活框架 (JAF)。

              您可以从 Java 的标准网站(或使用 Maven 或类似工具)下载最新版本的 JavaMail 和 JAF。

              现在,要发送一封简单的邮件,您必须执行以下操作:

              import java.util.*;
              import javax.mail.*;
              import javax.mail.internet.*;
              import javax.activation.*;
              
              public class SendEmail {
              
                 public static void main(String [] args) {    
                    // Recipient's email ID needs to be mentioned.
                    String to = "abcd@gmail.com";
              
                    // Sender's email ID needs to be mentioned
                    String from = "web@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);
              
                    // 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("This is the Subject Line!");
              
                       // Now set the actual message
                       message.setText("This is actual message");
              
                       // Send message
                       Transport.send(message);
                       System.out.println("Sent message successfully....");
                    } catch (MessagingException mex) {
                       mex.printStackTrace();
                    }
                 }
              }
              

              查看更多Java mail sending examples

              【讨论】:

                猜你喜欢
                • 2017-03-02
                • 2013-11-04
                • 2013-04-13
                • 2012-09-11
                • 2018-01-28
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多