简体   繁体   中英

How do I send a email with java?

I am trying to send a email using java mail. But when I run the code bellow I get a ton of errors. Can you explain to me why the code is not working. So what I am trying to do is to send a email using a java. If there is any other way can you please tell me bellow. My guess is something is wrong about the smpt server. I am new to stack overflow so please forgive me if I have not wrote the question correctly.

Edit: I now understand what is wrong I do not have a SMPT server running on my local host. Can someone explain how to create a SMPT server for free.

These are the errors I get...

/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

This is my java code....

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

Setup a Local Only SMTP Email Server (Linux, Unix, Mac)

1 - Point localhost.com to your machine

Most of programs will not accept an email using just @localhost as domain. So, edit /etc/hosts file to make the domain localhost.com point to your machine, including this content to the file:

127.0.0.1 localhost.com

2 - Install Postfix

Fedora/CentOS/RHEL: sudo yum install postfix

Ubuntu: sudo apt-get install postfix

MacOSX: Postfix is already installed by default.

3 - Configure Postfix to Local only

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 - Configure a Catch-all Address

Enabling this, you can use any email address ending with "@localhost" or "@localhost.com".

Example: here, my unique account is rael@localhost.com. But while testing systems, I can use any address like joe@localhost.com, foo@localhost.com, etc, because all will be redirected to 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 - Install Thunderbird

Ubuntu: sudo apt-get install thunderbird

6 - Configure Thunderbird

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 - Start your Mail Spool file

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM