HelloWorld系列-在Java中Send Email

来源:互联网 发布:淘宝电脑可靠么 编辑:程序博客网 时间:2024/04/28 21:05
运行这个例子需要activation.jar和mail.jar这两个包。

package demo.email;

import java.security.Security;
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.InternetAddress;
import javax.mail.internet.MimeMessage;
 
public class EmailDemo {
 
    
private static final String GMAIL_SMTP_HOST_NAME = "smtp.gmail.com";    
    
private static final String GMAIL_SMTP_PORT = "465";
    
private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    
    
    
public static void main(String args[]) throws Exception {

        String emailBody 
= "A Simple Email Demo! Put the email content here.  ";
        String emailSubject 
= "Hello World!";
        String emailFrom 
= ""// put your email address here 
        String[] sendTo = {"leon.7mx@gmail.com"};

        Security.addProvider(
new com.sun.net.ssl.internal.ssl.Provider());
 
        
new EmailDemo().sendSSLMessage(sendTo, emailSubject,emailBody, emailFrom);
        
        System.out.println(
"Sucessfully Sent mail to All Users");
    }

 
    
public void sendSSLMessage(String recipients[], String subject,
            String body, String from) 
throws MessagingException {
        
boolean debug = true;
        
        Properties props 
= new Properties();
        props.put(
"mail.smtp.host", GMAIL_SMTP_HOST_NAME);
        props.put(
"mail.smtp.auth""true");
        props.put(
"mail.debug""true");
        props.put(
"mail.smtp.port", GMAIL_SMTP_PORT);
        props.put(
"mail.smtp.socketFactory.port", GMAIL_SMTP_PORT);
        props.put(
"mail.smtp.socketFactory.class", SSL_FACTORY);
        props.put(
"mail.smtp.socketFactory.fallback""false");
 
        Session session 
= Session.getDefaultInstance(props,
                
new javax.mail.Authenticator() {
 
                    
protected PasswordAuthentication getPasswordAuthentication() {
                        
// put your gmail account & password here
                        return new PasswordAuthentication("your account""your password");
                    }

                }
);
 
        session.setDebug(debug);
 
        Message msg 
= new MimeMessage(session);
        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);
 
        
// Setting the Subject and Content Type
        msg.setSubject(subject);
        msg.setContent(body, 
"text/plain");
        Transport.send(msg);
    }

}