28

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

How do I send an SMTP Message from Java?

Community
  • 1
  • 1
Allain Lalonde
  • 91,574
  • 70
  • 187
  • 238

6 Answers6

37

Here's an example for Gmail smtp:

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("mail@tovare.com"));;
        msg.setRecipients(Message.RecipientType.TO,
        InternetAddress.parse("tov.are.jacobsen@iss.no", 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", "admin@tovare.com", "<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

jrmullen
  • 346
  • 5
  • 21
tovare
  • 4,027
  • 5
  • 29
  • 30
  • 1
    The sun mail dependency makes me a little nervous here--what if I'm using a non-sun JRE? – Brian Warshaw Dec 10 '14 at 13:47
  • Yes, the Java Mail API requires protocol Implementations and the bundled reference implementations are named sun, but part of the official distribution. These are pure java which should work well on any java implementations. It's not a proprietary feature from a vendor. – tovare Dec 11 '14 at 14:49
  • It may be that you can skip the import statement of com.sun :) – tovare Dec 11 '14 at 14:52
  • That's good--because I can't even resolve `com.sun.mail` in Eclipse on Windows. That makes me less than optimistic for the IBM jre on an AIX box, where we've had prior issues with trying to use `com.sun` packages. – Brian Warshaw Dec 11 '14 at 18:19
  • Another question--what package contains `SMTPTransport`? Is that why you imported the `com.sun.mail.smtp` package? – Brian Warshaw Dec 11 '14 at 18:20
  • OK, last comment, I hope :-) The only thing your answer is missing at this point is telling folks that JavaMail needs to be obtained, since it isn't bundled with the jdk. After I downloaded and put in my buildpath, I even have the `com.sun.mail` packages :-) – Brian Warshaw Dec 11 '14 at 18:26
  • I reconfigured the answer to community wiki. Feel free to add your experience :-) Also, I noticed that the code might be even more generic using the login in the send method in Transport, rather than using the provider specific SMTPTransport. – tovare Dec 12 '14 at 18:57
  • Passwords should not be hardcoded. Bad practice. – Ross Verry Nov 30 '16 at 12:44
  • but I always wonder where else I could put passwords like that? – xeruf Sep 19 '17 at 20:58
  • Suggest to change throws statement to just: 'throws MessagingException'. In addition, need to make sure to import javax.mail, i.e. if using gradle, add the following to your build.gradle: compile 'com.sun.mail:javax.mail:1.5.5' – AmitW Oct 01 '17 at 15:03
  • 1
    @AmitW, I agree "throws Exception" in my example is not a good way to deal with exceptions. – tovare Oct 02 '17 at 19:15
6

Another way is to use aspirin (https://github.com/masukomi/aspirin) 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
  • 857
  • 7
  • 8
Brad at Kademi
  • 1,300
  • 8
  • 7
3

Please see this post

How can I send an email by Java application using GMail, Yahoo, or Hotmail?

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

Community
  • 1
  • 1
Ryan Lanciaux
  • 5,965
  • 2
  • 37
  • 49
2

See the JavaMail API and associated javadocs.

Gray
  • 115,027
  • 24
  • 293
  • 354
Mason
  • 8,767
  • 10
  • 33
  • 34
2

See the following tutorial at Java Practices.

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

Jorge Ferreira
  • 96,051
  • 25
  • 122
  • 132
1
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*; 

public void postMail(String recipients[], String subject,
    String message , String from) throws MessagingException {

    //Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.jcom.net");

    // create some properties and get the default Session
    Session session = Session.getDefaultInstance(props, null);
    session.setDebug(false);

    // create a message
    Message msg = new MimeMessage(session);

    // set the from and to address
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);

    InternetAddress[] addressTo = new InternetAddress[recipients.length]; 
    for (int i = 0; i < recipients.length; i++) {
        addressTo[i] = new InternetAddress(recipients[i]);
    }
    msg.setRecipients(Message.RecipientType.TO, addressTo);

    // Optional : You can also set your custom headers in the Email if you Want
    msg.addHeader("MyHeaderName", "myHeaderValue");

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, "text/plain");
    Transport.send(msg);
}
Emil Sierżęga
  • 1,785
  • 2
  • 31
  • 38
user527619
  • 89
  • 1
  • 1
  • 6