使用JAVA发送邮件

使用JAVA发送邮件,java,smtp,jakarta-mail,Java,Smtp,Jakarta Mail,嗨,我想用java发送一封简单的邮件。。所以我下载了mail.jar和activation.jar文件,并编写了发送该文件的简单程序 我的简单邮件程序编译成功。。 但是当我运行时,它显示以下错误 javax.mail.MessaginException:无法连接到SMTP主机:localhost,端口:25; 嵌套异常是: java.net.ConnectException:连接被拒绝:连接 我的疑问是如何找到我的电脑的SMTP服务器名称?我在那个网站上搜索了一下,但什么也没弄清楚 请让我朝正确

嗨,我想用java发送一封简单的邮件。。所以我下载了mail.jar和activation.jar文件,并编写了发送该文件的简单程序

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

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

我的疑问是如何找到我的电脑的SMTP服务器名称?我在那个网站上搜索了一下,但什么也没弄清楚

请让我朝正确的方向旅行

关于


Xavier KCB

如果要连接到本地主机,您需要在PC或服务器上安装并运行SMTP服务器。
Windows和Linux有很多免费的。你的电脑不必使用SMTP服务器名称,你必须使用外部电子邮件服务器,例如gmail、yahoo等。你可以在电脑上设置邮件服务器,但这是不可能的。在您的情况下,您必须在免费邮件系统中注册新电子邮件,并使用它的smtp服务器和端口。 您可以在谷歌上搜索更多关于JavaMail API示例的信息:,

假设您正在使用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();
        }
    }
}
package ripon.java.mail;
导入javax.mail.*;
导入javax.mail.internet.*;
导入java.util.*;
公共类从Gmail发送{
公共静态void main(字符串参数[]){
试一试{
String host=“smtp.gmail.com”;
字符串from=”ripontest@gmail.com";
字符串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”);
字符串[]到={”riponalwasim@gmail.com"};
Session Session=Session.getDefaultInstance(props,null);
MimeMessage message=新MimeMessage(会话);
message.setFrom(新的InternetAddress(from));
InternetAddress[]toAddress=新的InternetAddress[to.length];
//获取地址数组的步骤
对于(int i=0;i
您首先需要有一个电子邮件服务器。 所以请使用一些like,这是免费的。 请注意自动禁止选项,它可以关闭,否则会毁了你的一天

安装和设置,非常简单

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

选中此项:

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

在所有事情上都要提到这一点。这是一个非常好的教程,将指导您完成整个过程。寻找某物时的良好参考:

请不要用一些GMail帐户来开发这个功能,他们的服务器不会合作,因为你正在制造很多麻烦(连接太多,经常因为错误登录而被禁止等)。

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


您可以在本地免费启用SendGrid服务,也可以在开发该软件的特定PaaS上立即部署它。

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

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

  • 1) 正如许多其他成员已经提到的那样,更正主机详细信息。25默认端口,如果不相同,请更改此端口
  • 2) 检查您正在访问的服务器是否要求进行身份验证或 不代码中有更多关于这方面的内容
  • 3) 请将mail.debug放入 属性,以了解代码和 邮件服务器。代码中有更多关于这方面的内容
我的代码:

通过本地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...");
    }
}
import java.util.Properties;
导入javax.activation.DataHandler;
导入javax.activation.DataSource;
导入javax.activation.FileDataSource;
导入javax.mail.Message;
导入javax.mail.MessaginException;
导入javax.mail.Multipart;
导入javax.mail.Session;
导入javax.mail.Transport;
导入javax.mail.internet.AddressException;
导入javax.mail.internet.InternetAddress;
导入javax.mail.internet.MimeBodyPart;
导入javax.mail.internet.mimessage;
导入javax.mail.internet.MimeMultipart;
公共类邮件发送者{
公共最终字符串mailServerAddress;
公共最终int邮件服务器端口;
公共最终字符串发送者地址;
public MailSender(字符串mailServerAddress、int mailServerPort、字符串senderAddress){
this.senderAddress=senderAddress;
这是mailSe
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...");
    }
}
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);

    }

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