0

I am using Eclipse LUNA package. I need to send mail using service provider called "MAILGUN". In that "www.mailgun.com" website, they have given a API code to send or receive mails using the available service. The code is as follows:

import java.awt.PageAttributes.MediaType;
import java.io.*;
import java.net.*;
import javax.annotation.PostConstruct;
import javax.ws.rs.POST;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
import com.sun.jersey.core.util.MultivaluedMapImpl;

public class Mil_connect1 {
    public static ClientResponse SendSimpleMessage() {
       Client client = Client.create();
       client.addFilter(new HTTPBasicAuthFilter("api","key-***********"));
       com.sun.jersey.api.client.WebResource webResource=client.resource("https://api.mailgun.net/v2/samples.mailgun.org" +"/messages");
       MultivaluedMapImpl formData = new MultivaluedMapImpl();
       formData.add("from", "skalyanasundaram1994@gmail.com");
       formData.add("to", "bharani829@gmail.com");
       formData.add("subject", "Hello");
       formData.add("text", "Testing some Mailgun awesomness!");
       return null;
    }
    public static void main(String[] args) {
        SendSimpleMessage();
        System.out.println("Success");
    }
}

Here, Instead of "key-*" my service provider secret key will be replaced. My output was:

    Success

But, mail cannot be sent. Please kindly guide me how to do that using mailgun as service provider...

kalyan
  • 37
  • 1
  • 6

3 Answers3

2

Have you tried changing "samples.mailgun.org" to your domain name?

Also, you are not actually posting your data:

private final String baseURL = "https://api.mailgun.net/v2/";

private String mailgunAPIKey;

private <T> WebTarget createPrivateClient() {
    final Client client = ClientBuilder.newClient();
    client.register(HttpAuthenticationFeature.basic("api", this.mailgunAPIKey));
    return client.target(this.baseURL);
}

protected void fireMailGun(final MultivaluedMap<String, String> postData) {
    this.createPrivateClient().path("YOUR_DOMAIN/messages")
                              .request()
                              .post(Entity.form(postData));
}

Maven Dependency:

    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-client</artifactId>
        <version>2.10</version>
    </dependency>
dannrob
  • 1,061
  • 9
  • 10
  • Yes, I have also tried to change my client.resource to "samples.mailgun.org".... But it seems to give the same result... No error and no output too... – kalyan Jul 28 '14 at 17:14
  • i've update my answer with code that i use that works, try that – dannrob Jul 28 '14 at 17:15
  • I have one doubt..... We have not logged in to out mail... say: "skalyanasundaram1994@gmail.com"... Then how can we send mail from this java code without any password... – kalyan Jul 28 '14 at 17:22
  • Mailgun will send the mail, it will just set the from header as "skalyanasundaram1994@gmail.com". – dannrob Jul 28 '14 at 17:24
  • Ok... when the process was successful.... Then, will the change is reflected in the SENT MAIL of the "skalyanasundaram1994@gmail.com" or not????? – kalyan Jul 28 '14 at 17:27
  • This would be a ridiculous security flaw if I could put an email into someone's sent mail!!! You are not actually using the gmail account for sending mail, you are just pretending you are, just like a spammer would. I would read up on how email SMTP, etc.. works – dannrob Jul 28 '14 at 17:29
  • Yes, please clear my doubt also.... Wheather, my doubt was correct or not....???? – kalyan Jul 28 '14 at 17:34
  • I have also followed your code too... But, still the same result was repeating..... Kindly Guide me... I am in need of using this service provider .... – kalyan Jul 28 '14 at 18:05
  • Thanks for your response.... I have successfully send mails using Mailgun...... I have changed the default domain name to "my domain name".... – kalyan Jul 28 '14 at 18:43
1

Please try this code. I am using below code and its working fine.

    Properties props = System.getProperties();
    props.put("mail.smtps.host","smtp.mailgun.org");
    props.put("mail.smtps.auth","true");
    Session session = Session.getInstance(props, null);
    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress("abc@gmail.com"));
    msg.setRecipients(Message.RecipientType.TO,
    InternetAddress.parse("xyz@gmail.com", false));
    msg.setSubject(subject);
    msg.setText(body);
    msg.setRecipients(Message.RecipientType.CC,InternetAddress.parse("abc@gmail.com"));
    msg.setContent(body, "text/html");
    SMTPTransport t =  (SMTPTransport)session.getTransport("smtps");
    t.connect("smtp.mailgun.com", "postmaster@sandbox***********.mailgun.org", "0ae971*********");
    t.sendMessage(msg, msg.getAllRecipients());
    System.out.println("Response: " + t.getLastServerResponse());
    t.close();
shan
  • 186
  • 2
  • 14
  • I suggest you to use the REST api which is easier and less error prone. Hey, [they say so](https://documentation.mailgun.com/faqs.html#should-i-use-smtp-or-the-http-api). – sargue Dec 22 '15 at 18:03
1

Just in case someone finds this useful, I'm developing a Java mail library to easily send email messages using Mailgun.

https://github.com/sargue/mailgun

It will allow to send messages like this:

MailBuilder.using(configuration)
    .to("marty@mcfly.com")
    .subject("This is the subject")
    .text("Hello world!")
    .build()
    .send();

Even file attachments are easy:

MailBuilder.using(configuration)
    .to("marty@mcfly.com")
    .subject("This message has an text attachment")
    .text("Please find attached a file.")
    .multipart()
    .attachment(new File("/path/to/image.jpg"))
    .build()
    .send();

There is also support for asynchronous message sending and a HTML mail helper. It is a young project, feedback is very welcome.

sargue
  • 5,695
  • 3
  • 28
  • 43