DEV Community

Bryan Douglas
Bryan Douglas

Posted on

Sending an email within a Java Application

Hi all,

I decided to pick up the old textbook and start to learn more about Java (I know, I should understand most of it by this point :D).

I am focusing on the interaction between the application and sending of emails. As I eventually want to port this code to android studio and use it to create an email application for android.

Here is the code:

public static void main(String[] args) {
        // Recipient's email ID needs to be mentioned.
        String to = "example";

        // Sender's email ID needs to be mentioned
        String from = "example";

        // Setting the host and port
        String host = "smtp.gmail.com";
        String port = "465";

        // Get system properties
        Properties properties = System.getProperties();

        // Setup mail server
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.smtp.port", port);

        properties.setProperty("mail.user", "example");
        properties.setProperty("mail.password", "example");

        // 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();
        }
    }
Enter fullscreen mode Exit fullscreen mode

My code no longer fails to connect or times out, it just continues to run (likely until my system crashes). After stepping through the code - it seems to hang right at

Transport.send(message);
Enter fullscreen mode Exit fullscreen mode

Since it never throws an error, I cannot get an exception code or any details.

If you guys could take a look at my code and point out any mistakes, that'd be awesome.

Thanks!!!

Top comments (0)