Hi friends. I used this program to send mails via JavaMail API. Thought it could be useful.

I have put system.out.println just for verification. U can remove those if u want.


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

public class SendMail {
	public static boolean send(String[] to) {
		System.out.println("send mail: " + to);
		try {
			String host = "smtp.mail.yahoo.co.in";
			String from = "user name";
			Properties props = System.getProperties();
			props.put("mail.smtp.host", host);
			props.put("mail.smtp.user", from);
			props.put("mail.smtp.password", "asdfgh");
			props.put("mail.smtp.port", "587"); // 587 is the port number of yahoo mail
			props.put("mail.smtp.auth", "true");

			Session session = Session.getDefaultInstance(props, null);
			MimeMessage message = new MimeMessage(session);
			message.setFrom(new InternetAddress(from));

			InternetAddress[] to_address = new InternetAddress[to.length];
			int i = 0;
			// To get the array of addresses
			while (to[i] != null) {
				to_address[i] = new InternetAddress(to[i]);
				i++;
			}
			System.out.println(Message.RecipientType.TO);
			i = 0;
			while (to_address[i] != null) {
				message.addRecipient(Message.RecipientType.TO, to_address[i]);
				i++;
			}
			message.setSubject("sending in a group");
			message.setText("Welcome to JavaMail");
			Transport transport = session.getTransport("smtp");
			transport.connect("smtp.mail.yahoo.co.in", "user name", "asdfgh");
			transport.sendMessage(message, message.getAllRecipients());
			transport.close();
			return true;
		} catch (Exception e) {
			System.out.println("this is the error: " + e);
			return false;
		}
	}

	public static void main(String args[]) {
		String[] address = { "sample1@sample.com", "sample2@sample.com" };
		new SendMail().send(address);
	}
}

Advertisements