tags:

views:

1024

answers:

7

How do I send an SMTP Message from Java?

+1  A: 

See the JavaMail API

Mason
A: 

Use the JavaMail API.

PaulF
+3  A: 

Please see this post

http://stackoverflow.com/questions/46663/how-do-you-send-email-from-a-java-app-using-gmail

It is specific to gmail but you can substitute your smtp credentials.

Ryan Lanciaux
A: 

See the following tutorial at Java Practices.

http://www.javapractices.com/topic/TopicAction.do?Id=144

smink
A: 

Try google before asking...

http://www.developerfusion.co.uk/show/1975/

mmattax
Dude, SO is supposed to be a resource for developers. And this specific question hadn't been answered.
Allain Lalonde
+5  A: 

Here's an example for Gmail smtp:

http://tovare.com/articles/learnhowtosendemailviagmailfromjavain120seconds/

/*
 *
 */

import java.io.*;
import java.net.InetAddress;
import java.util.Properties;
import java.util.Date;

import javax.mail.*;

import javax.mail.internet.*;

import com.sun.mail.smtp.*;


public class Distribution {

    public static void main(String args[]) throws Exception {
        Properties props = System.getProperties();
        props.put("mail.smtps.host","smtp.gmail.com");
        props.put("mail.smtps.auth","true");
        Session session = Session.getInstance(props, null);
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("[email protected]"));;
        msg.setRecipients(Message.RecipientType.TO,
        InternetAddress.parse("[email protected]", false));
        msg.setSubject("Heisann "+System.currentTimeMillis());
        msg.setText("Med vennlig hilsennTov Are Jacobsen");
        msg.setHeader("X-Mailer", "Tov Are's program");
        msg.setSentDate(new Date());
        SMTPTransport t =
            (SMTPTransport)session.getTransport("smtps");
        t.connect("smtp.gmail.com", "[email protected]", "<insert password here>");
        t.sendMessage(msg, msg.getAllRecipients());
        System.out.println("Response: " + t.getLastServerResponse());
        t.close();
    }
}

Now, do it this way only if you would like to keep your project dependencies to a minimum, otherwise i can warmly recommend using classes from apache

http://commons.apache.org/email/

Regards

Tov Are Jacobsen

tovare
+2  A: 

Another way is to use aspirin (http://aspirin.dev.java.net/) like this:

MailQue.queMail(MimeMessage message)

..after having constructed your mimemessage as above.

Aspirin is an smtp 'server' so you don't have to configure it. But note that sending email to a broad set of recipients isnt as simple as it appears because of the many different spam filtering rules receiving mail servers and client applications apply.

brad