簡単なメールコードの送信

2332 ワード



package send;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class SendMail {
	Properties props = new Properties();
	MimeMessage message;
	public  final static String SMTP="mail.hollycrm.com";
	public final static int PORT=25;
	public final static String USER_NAME="**@hollycrm.com";
	public final static String PASSWORD="**";
//	public  final static String SMTP="smtp.gmail.com";
//	public final static int PORT=465;
//	public final static String USER_NAME="**@gmail.com";
//	public final static String PASSWORD="**";
	public final static String TO_ADDRESS="**@qq.com";
	
	public void init(){
		props.put("mail.smtp.host", SMTP);
		props.put("mail.smtp.auth", "true");
		Authenticator auth = new MyAuthenticator();
		Session session = Session.getDefaultInstance(props, auth);
		session.setDebug(true);
		message = new MimeMessage(session);
		try{
			
			message.setFrom(new InternetAddress(USER_NAME));
			message.setRecipient(Message.RecipientType.TO, new InternetAddress(TO_ADDRESS));
			//message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(TO_ADDRESS,false));
			message.setSubject(" ");
			//message.setContent(" ", "text/plain");
			message.setContent(" ", "text/plain;charset=gb2312");
			message.saveChanges();
			Transport tran = session.getTransport("smtp");
			tran.connect(SMTP,PORT, USER_NAME, PASSWORD);
			tran.sendMessage(message, message.getAllRecipients());
			tran.close();
		}catch(MessagingException me){
			me.printStackTrace();
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SendMail sendMail = new SendMail();
		sendMail.init();
	}
	
	class MyAuthenticator extends Authenticator{
		public PasswordAuthentication getPasswordAuthentiaction(){
			return new PasswordAuthentication(USER_NAME,PASSWORD);
		}
	}

}