Java Mail SMTP发送邮件实例 Sending Email with SMTP using Java Mail

Categories: Java; Tagged with: ; @ September 13th, 2012 18:09

The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications. The JavaMail API is available as an optional package for use with Java SE platform and is also included in the Java EE platform.

Download JavaMailAPI: http://www.oracle.com/technetwork/java/javamail/index.html

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


public class JavaMailTest {
	
	public static void main(String[] args) throws AddressException, MessagingException {
			String host = "smtp server addr.";
		    final String from = "[email protected]";
		    final String password = "password";
		    String to = "abc@_example.com";

		    // Get system properties
		    Properties props = System.getProperties();
		    // Setup mail server
		    props.setProperty("mail.smtp.host", host);
		    props.setProperty("mail.smtp.auth", "true");
		    props.setProperty("mail.smtp.port", "25");

		    // Get session
		    Session session = Session.getInstance(props,
		  		  new javax.mail.Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(from, password);
				}
			  });

		    // Prepare message
		    MimeMessage message = new MimeMessage(session);
		    message.setFrom(new InternetAddress(from));
		    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
		    message.setSubject("Hello JavaMail");
		    message.setText("Test Email from JavaMail");
		    
		    // Send message
		    Transport.send(message);
	}

}

<->



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.