Allain Lalonde Allain Lalonde - 1 year ago 51
Java Question

How do I send an SMTP Message from Java?

Possible Duplicate:

How do you send email from a Java app using Gmail?

How do I send an SMTP Message from Java?

Answer Source

Here's an example for Gmail smtp:


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();
        Session session = Session.getInstance(props, null);
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(""));;
        InternetAddress.parse("", 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 =
        t.connect("", "", "<insert password here>");
        t.sendMessage(msg, msg.getAllRecipients());
        System.out.println("Response: " + t.getLastServerResponse());

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


Tov Are Jacobsen