How to use sendmail in Java?

G

Guest

I have the following Perl code that works for sending email from a
Linux machine:

open(SENDMAIL, "|/usr/sbin/sendmail -t") or die "Unable to open
sendmail";
print(SENDMAIL "To: $recipients\n");
print(SENDMAIL "Subject: Test Results\n");
print(SENDMAIL "\n");
print(SENDMAIL "here are the results\n");
close(SENDMAIL);

I want to do the same thing in Java, but when I try to open that file,
I get "java.io.FileNotFoundException: !/usr/sbin/sendmail -t (No such
file or directory)"

So then I tried to use the JavaMail API, and I got the following
exception:

send failed, exception: javax.mail.SendFailedException: Sending
failed;
nested exception is:
class javax.mail.MessagingException: Could not connect to SMTP
host: 10.11.8.45, port: 25;
nested exception is:
java.net.ConnectException: Connection refused

I did a ps -fea and I see that sendmail is running and accepting
connections. netstat -an shows that port 25 is listening. Iptables
is not running so it isn't a firewall issue. I'm trying to run the
Java program from the same machine where sendmail is running. Any
idea why JavaMail can't connect?

This is the code I'm using:

java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.host", "10.11.8.45");
props.put("mail.from", "sender@domain");
Session session = Session.getInstance(props, null);

try {
MimeMessage msg = new MimeMessage(session);
msg.setFrom();
msg.setRecipients(Message.RecipientType.TO,
"(e-mail address removed)");
msg.setSubject("JavaMail hello world example");
msg.setSentDate(new java.util.Date());
msg.setText("Hello, world!\n");
Transport.send(msg);
}
catch (MessagingException mex) {
System.out.println("send failed, exception: " + mex);
}
 
N

Nigel Wade

I did a ps -fea and I see that sendmail is running and accepting
connections. netstat -an shows that port 25 is listening. Iptables
is not running so it isn't a firewall issue. I'm trying to run the
Java program from the same machine where sendmail is running. Any
idea why JavaMail can't connect?

This is the code I'm using:

java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.host", "10.11.8.45");

What does netstat show as the listening address? By default, unless you have a
fully configured MTA, sendmail will only listen on the loopback address. The
prevents it from acting as an open relay.

Try specifying 127.0.0.1 as the mail.smtp.host.
 
G

Guest

What does netstat show as the listening address? By default, unless you have a
fully configured MTA, sendmail will only listen on the loopback address. The
prevents it from acting as an open relay.

Try specifying 127.0.0.1 as the mail.smtp.host.

You were right. Thanks!
 
R

Roedy Green

nested exception is:
class javax.mail.MessagingException: Could not connect to SMTP
host: 10.11.8.45, port: 25;
nested exception is:
java.net.ConnectException: Connection refused

Sounds like you did not include your password. See
http://mindprod.com/products.html#BULK
look at my code for logging on in Bulk.java.


// note that send needs a password.
Properties props = System.getProperties();
if ( NEED_PASSWORD_TO_SEND )
{
props.setProperty( "mail.smtp.auth", "true" );
}
....
store = session.getStore( RECEIVE_PROTOCOL );
store.connect( RECEIVE_HOST,
RECEIVE_PORT,
RECEIVE_LOGIN_ID,
RECEIVE_PASSWORD );

....
Transport transport = session.getTransport( SEND_PROTOCOL );
transport.connect( SEND_HOST,
SEND_PORT,
SEND_LOGIN_ID,
SEND_PASSWORD );

Also try turning on debugging so you can watch it more detail what is
happening.
 
L

Lothar Kimmeringer

Roedy said:
Sounds like you did not include your password.

How do you provide a password when opening a socket?


Regards, Lothar
--
Lothar Kimmeringer E-Mail: (e-mail address removed)
PGP-encrypted mails preferred (Key-ID: 0x8BC3CD81)

Always remember: The answer is forty-two, there can only be wrong
questions!
 
L

Lothar Kimmeringer

open(SENDMAIL, "|/usr/sbin/sendmail -t") or die "Unable to open
sendmail";
print(SENDMAIL "To: $recipients\n");
print(SENDMAIL "Subject: Test Results\n");
print(SENDMAIL "\n");
print(SENDMAIL "here are the results\n");
close(SENDMAIL);

I want to do the same thing in Java, but when I try to open that file,
I get "java.io.FileNotFoundException: !/usr/sbin/sendmail -t (No such
file or directory)"

In perl you're not opening a file in the first line. The pipe
at the beginning of the "filename" signifies that you're executing
a process, /usr/sbin/sendmail with the parameter "-t".

How to solve the whole thing in a purely java-based way you
already found out (with the help of Nigel, so I show you how
to do the above thing just to complete the topic ;-)

Process p = Runtime.getRuntime().exec(new String[]{
"/usr/sbin/sendmail",
"-t"
});
OutputStreamWriter os = new OutputStreamWriter(p.getOutputStream(), "8859_1");
os.write("To: ");
os.write(recipients);
os.write("\n");
os.write("Subject: Test Results\n");
os.write("\n");
os.write("here are the results\n");
os.close();
p.waitFor();

If sendmail is doing output on STDOUT or STDERR you have to read
that (e.g. in a Thread to be able to wait for the end of the
process). But because the JavaMail API is to be prefered this
is purely for information and not intended to be used in production.


Regards, Lothar
--
Lothar Kimmeringer E-Mail: (e-mail address removed)
PGP-encrypted mails preferred (Key-ID: 0x8BC3CD81)

Always remember: The answer is forty-two, there can only be wrong
questions!
 
?

=?ISO-8859-1?Q?Arne_Vajh=F8j?=

Roedy said:
I already posted the code. I pointed you to a complete program.

I think the important part above is "when opening a socket"
based on the exception which was:
java.net.ConnectException: Connection refused

Arne
 
R

Roedy Green

I think the important part above is "when opening a socket"
based on the exception which was:
java.net.ConnectException: Connection refused

You don't open a socket. You play with JavaMail objects, such as
Store, Transport and Session. JavaMail manages the socket.
 
?

=?ISO-8859-1?Q?Arne_Vajh=F8j?=

Roedy said:
You don't open a socket. You play with JavaMail objects, such as
Store, Transport and Session. JavaMail manages the socket.

True.

But the JavaMail classes eventually use a socket.

The point is that the exception indicates that it
happen at connect time.

Before it is possible to even send a password.

Arne
 
M

microsoft_geek

I am giving here the full source code by using this code i have
successfully sent mail to any address. You have to set the classpath
of the JavaMail API first... then try this code... with proper values
in the fields

//here is the code
//Author - A. B. Mondal([email protected])


import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

// Send a simple, single part, text/plain e-mail

public class TestEmail {

public static void main(String[] args) {

// SUBSTITUTE YOUR EMAIL ADDRESSES HERE!!!
String to = "(e-mail address removed)";
String from = "(e-mail address removed)";


// SUBSTITUTE YOUR ISP'S MAIL SERVER HERE!!!
String host = "mail.infobase.in";

// Create properties, get Session
Properties props = new Properties();

// If using static Transport.send(),
// need to specify which host to send it to
props.put("mail.smtp.host", host);

// To see what is going on behind the scene
props.put("mail.debug", "true");
Session session = Session.getInstance(props);

try {
// Instantiate a message
Message msg = new MimeMessage(session);

//Set message attributes
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject("UR SUBJECT");
msg.setSentDate(new Date());

// Set message content
msg.setText("This is a test of sending a " +
"plain text e-mail through Java.\n" +
"BY YOU");

//Send the message
Transport.send(msg);
}
catch (MessagingException mex) {
// Prints all nested (chained) exceptions as well
mex.printStackTrace();
}
}
}//End of class

Regards
Aurobindo
Java Developer
 
L

Lothar Kimmeringer

Roedy said:
I already posted the code.

Yes and if you point the program to an unused port, what
error-message do you get? You will get exactly the exception
class javax.mail.MessagingException: Could not connect to SMTP host:
[somewhere], port: [someport];
nested exception is:
java.net.ConnectException: Connection refused

Of course this needs a correctly adminstered network where requests
to ports are not filtered by intermediate "firewalls". Otherwise
you will get a "request timed out".
I pointed you to a complete program.

So? The program will most likely be the same as void.no.spam.com
was using for his test resulting to the exception. Problem is
that you don't really read the postings here but just see the
keywords and post links to your pages all the time without caring
if it fits the current problem or not.

Mostly it works, but quite often not. This is one example (of many).


Regards, Lothar
--
Lothar Kimmeringer E-Mail: (e-mail address removed)
PGP-encrypted mails preferred (Key-ID: 0x8BC3CD81)

Always remember: The answer is forty-two, there can only be wrong
questions!
 
R

Roedy Green

But the JavaMail classes eventually use a socket.

The point is that the exception indicates that it
happen at connect time.

I suggested turning on debug. You can then see if the password has
even been sent. If you can't even make the raw socket connect, you may
have the url or port wrong. Check that combo out with a commercial
mail program.

I discovered my ISP, Telus, is BLOCKING my email to/from any but THEIR
mail servers. The solution is to use a non-standard port so they don't
see it as email. This is well-intentioned -- to discourage spammers,
but it also stops you from having SMTP/POP3 accounts out on the web.

You may be having similar trouble.
 
R

Roedy Green

I am giving here the full source code by using this code i have
successfully sent mail to any address.

Nowadays you often need a password to send mail, unless that mail is
to the domain of the mailserver.

There are several password schemes.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,992
Messages
2,570,220
Members
46,805
Latest member
ClydeHeld1

Latest Threads

Top