使用JAVA发送邮件

时间:2012-03-10 10:53:31

标签: java smtp javamail

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

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

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

我怀疑如何为我的电脑找到SMTP服务器名称?我在网站搜索但没有得到任何清楚的东西..

请让我朝正确的方向旅行......

关于

Xavier KCB

9 个答案:

答案 0 :(得分:2)

您不必为您的PC使用SMTP服务器名称,您必须使用外部电子邮件服务器,例如,gmail,yahoo等。您可以在您的计算机上设置邮件服务器,但它不在题。在您的情况下,您必须在免费邮件系统中注册新电子邮件,并使用它smtp服务器和端口。 您可以更多地了解JavaMail API示例:cafeaulaitvipan

答案 1 :(得分:0)

假设您使用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();
        }
    }
}

答案 2 :(得分:0)

您需要先拥有电子邮件服务器。 所以请使用像http://www.hmailserver.com/这样的免费版。 请注意自动禁止选项,该选项可以关闭,否则会毁了你的一天。

安装和设置,非常简单。

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

选中此项:http://www.xmarks.com/site/www.digilife.be/quickreferences/PT/Fundamentals%2520of%2520the%2520JavaMail%2520API.pdf

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

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

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

使用某个GMail帐户开发 - 他们的服务器不会合作,因为你要麻烦很多(连接很多,不断禁止导致虚假登录等)

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

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

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

  • 1)正如许多其他成员已经提到的那样纠正主机细节。 25默认端口,如果不相同则更改。
  • 2)检查您要服务的服务器是否要求进行身份验证或 不。在代码中更多关于此。
  • 3)请将mail.debug放入 属性,以了解您的代码和代码之间究竟发生了什么 邮件服务器。更多关于这一点的代码。

我的代码:

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

答案 5 :(得分:0)

通过本地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...");
    }
}

答案 6 :(得分:0)

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

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

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

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

答案 7 :(得分:-1)

如果要连接到localhost,则需要在PC或服务器上安装并运行SMTP服务器。 Windows和Linux都有一堆免费的。

答案 8 :(得分:-1)

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

    }

}