Hello,
To use the code below you will need to get a copy of the java mail and activation API's and set your compiler up to use them.
There are 2 methods, one is the method you want which accepts parameters, the other is only for testing and uses strings in place of the variables.
If using tomcat you can compile this class and use it as a Java Bean, passing values from a JSP page to the bean.
I have also included an Authenticator class, I did not need this, but you may have to use it depending on your server settings.
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendApp
{
public static void send(String from, String to, String CC, String subject, String content)
throws AddressException, MessagingException
{
//You may need to change the IP below
String smtpHost = "127.0.0.1";
int smtpPort = 25;
// Create a mail session
java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port", ""+smtpPort);
props.put("mail.smtp.auth", "true");
// you may need authentication on your server:
// I have included this class below this one
// Authenticator auth = new SimpleAuthenticator();
Session session = Session.getDefaultInstance(props, auth);
// Construct the message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setRecipient(Message.RecipientType.CC, new InternetAddress(CC));
// You will need to add another parameter for BCC, I just tested it with the cc parameter
msg.setRecipient(Message.RecipientType.BCC, new InternetAddress(CC));
msg.setSubject(subject);
msg.setText(content);
// Send the message
Transport.send(msg);
}
public static void main(String[] args) throws Exception
{
// Send a test message with no variable parameters
// this will let you know if the API is working
send("From
[email protected]", "To
[email protected]", "cc
[email protected]", "Subject re: yourSubject", "Content A test message");
}
}
+++++++++++++++++++++++++++++++++++++++++
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SimpleAuthenticator extends Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
String username, password;
username = "user";
password = "pass";
return new PasswordAuthentication(username, password);
}
}