The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
April 2001

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

sending mail on linux using java

Posted by Dwayne Kemp on January 11, 2002 at 1:37 PM

> I want to send a mail using java in Linux Platform.The Machine is connected to Internet using a proxy and is behind a firewall.
> can anyone help me.

you will need the java mail package then get the activation.jar
file from sun i believe it is located in the ejb package.

you can use this code:

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.io.*;
import java.net.InetAddress;
import java.util.Properties;

public class sendmail
{
String content;

public sendmail(String message)
{
content = new String(message);
}

public void postMail( String recipients[ ], String subject, String message , String from)throws MessagingException
{
//you can set this to false if you like
boolean debug = true;

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

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

// 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("header", "value");

// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
//Transport.send(msg);
msg.saveChanges(); // implicit with send()
Transport transport = session.getTransport("smtp");
transport.connect("host","user","password");
transport.send(msg);
transport.close();

}

public static void main(String args[]) throws IOException
{
sendmail to = new sendmail("body of email");
String[] a = {"email or emails"};
try
{
to.postMail( a, "subject" , to.content , "who ever");
}
catch(MessagingException e)
{
e.printStackTrace();
}

}

you will also need to configure your host.allow file located under
/etc/hosts.allow with

smtp: "smtp server ip"



Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us