首页 > 解决方案 > 如何使用 java 发送电子邮件?

问题描述

我正在尝试使用 java 邮件发送电子邮件。但是当我运行下面的代码时,我得到了大量的错误。你能解释一下为什么代码不起作用。所以我想做的是使用java发送电子邮件。如果有其他方法可以请告诉我下面。我的猜测是 smpt 服务器有问题。我是堆栈溢出的新手,所以如果我没有正确写出问题,请原谅我。

编辑:我现在明白出了什么问题,我的本地主机上没有运行 SMPT 服务器。有人可以解释如何免费创建 SMPT 服务器。

这些是我得到的错误......

/home/theprogrmmer/.jdks/openjdk-15.0.1/bin/java -javaagent:/home/theprogrmmer/.local/share/JetBrains/Toolbox/apps/IDEA-U/ch-0/202.8194.7/lib/idea_rt.jar=44243:/home/theprogrmmer/.local/share/JetBrains/Toolbox/apps/IDEA-U/ch-0/202.8194.7/bin -Dfile.encoding=UTF-8 -classpath /home/theprogrmmer/IdeaProjects/practice 1/out/production/practice 1:/home/theprogrmmer/IdeaProjects/practice 1/lib/javax.ejb.jar:/home/theprogrmmer/IdeaProjects/practice 1/lib/javax.jms.jar:/home/theprogrmmer/IdeaProjects/practice 1/lib/javax.annotation.jar:/home/theprogrmmer/IdeaProjects/practice 1/lib/javax.persistence.jar:/home/theprogrmmer/IdeaProjects/practice 1/lib/javax.resource.jar:/home/theprogrmmer/IdeaProjects/practice 1/lib/javax.transaction.jar:/home/theprogrmmer/IdeaProjects/practice 1/lib/javax.servlet.jar:/home/theprogrmmer/IdeaProjects/practice 1/lib/javax.servlet.jsp.jar:/home/theprogrmmer/IdeaProjects/practice 1/lib/javax.servlet.jsp.jstl.jar:/home/theprogrmmer/IdeaProjects/practice 1/src/com/company/mail.jar:/home/theprogrmmer/IdeaProjects/practice 1/src/com/company/jaf-1.0.2/activation.jar com.company.SendEmail
javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
  nested exception is:
    java.net.ConnectException: Connection refused
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1961)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
    at javax.mail.Service.connect(Service.java:295)
    at javax.mail.Service.connect(Service.java:176)
    at javax.mail.Service.connect(Service.java:125)
    at javax.mail.Transport.send0(Transport.java:194)
    at javax.mail.Transport.send(Transport.java:124)
    at com.company.SendEmail.main(SendEmail.java:48)
Caused by: java.net.ConnectException: Connection refused
    at java.base/sun.nio.ch.Net.connect0(Native Method)
    at java.base/sun.nio.ch.Net.connect(Net.java:574)
    at java.base/sun.nio.ch.Net.connect(Net.java:563)
    at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:588)
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:333)
    at java.base/java.net.Socket.connect(Socket.java:648)
    at java.base/java.net.Socket.connect(Socket.java:597)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:321)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:237)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927)
    ... 7 more

这是我的java代码....

package com.company;

// File Name SendEmail.java

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

标签: javaemail

解决方案


设置仅限本地的 SMTP 电子邮件服务器(Linux、Unix、Mac)

1 - 将 localhost.com 指向您的机器

大多数程序不会接受仅使用 @localhost 作为域的电子邮件。因此,编辑 /etc/hosts 文件以使域 localhost.com 指向您的计算机,包括此文件的内容:

127.0.0.1 localhost.com

2 - 安装后缀

Fedora/CentOS/RHEL:sudo yum install postfix

Ubuntu:sudo apt-get install postfix

MacOSX:默认情况下已经安装了 Postfix。

3 - 仅将 Postfix 配置为本地

During postfix install process, the configure text dialog will display five options:

General type of mail configuration: 

No configuration
Internet Site
Internet with smarthost
Satellite system
Local only

Select "Local Only".

For the domain name, use the default suggested and finish the install.

4 - 配置包罗万象的地址

启用此功能后,您可以使用任何以“@localhost”或“@localhost.com”结尾的电子邮件地址。

示例:在这里,我的唯一帐户是 rael@localhost.com。但是在测试系统时,我可以使用任何地址,例如 joe@localhost.com、foo@localhost.com 等,因为所有地址都会被重定向到 rael@localhost.com

If not exists, create file /etc/postfix/virtual: sudo nano /etc/postfix/virtual
Add the following 2 lines content, replacing <your-user> with your Unix user account:

@localhost @localhost.com

Save and close the file.
Configure postifx to read this file:
    Open /etc/postfix/main.cf: sudo nano /etc/postfix/main.cf
    And check if this line is enabled, or add it if not exists: virtual_alias_maps = hash:/etc/postfix/virtual
Activate it: sudo postmap /etc/postfix/virtual
Reload postfix: sudo systemctl restart postfix
If you're under non systemd distro, like Ubuntu 14.04, service restart command probably is: sudo service postfix reload

5 - 安装雷鸟

Ubuntu:sudo apt-get 安装雷鸟

6 - 配置雷鸟

Skip the welcome screen (click in the button to use existing accounts);
Click in the Settings button at top right (similar to Chrome settings) then click on Preferences > Account Settings
Under Account Actions choose "Add Other Account"
Select "Unix Mailspool (Movemail)"
Your account will be <your-user>@localhost (of course, replace <your-user> with your user account). Don't use <your-user>@(none), use <your-user>@localhost
Ingoing and Outgoing server will be: localhost
Restart (close and reopen) Thunderbird.

7 - 启动您的 Mail Spool 文件

This step have two purposes: test your install and stop the Unable to locate mail spool file. message.
Using Thunderbird, send new email to <your-user>@localhost, replacing <your-user> with your user account
Click on "Get Mail"
Test catch-all: send new email to averagejoe@localhost
Click on "Get Mail" and you'll see the message at Inbox.

推荐阅读