java 发送mail

来源:互联网 发布:电脑网络不稳定老掉线 编辑:程序博客网 时间:2024/05/17 04:46
package zh;

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

public class SendMainl {
//smtp.sohu.com
    private static final String SMTP_HOST = "smtp.163.com";

    
private static final String SENDER_NAME = "熊猫飞天有限责任公司";

    
private static final String SENDER_EMAIL_ADDRESS = "mail@163.com";

    
public void sendConfirmation() {
        StringBuffer message 
= new StringBuffer();
        message.append(
"Hello!");
        message.append(
"哈哈!!");

        sendMessage(
"to@163.com""Sorry!java mail test", message.toString());
    }


    
protected void sendMessage(String recipient, String subject, String message) {
        Properties props 
= new Properties();
        props.put(
"mail.smtp.auth""true");
        props.put(
"mail.host", SMTP_HOST);
        props.put(
"mail.smtp.user""mail@163.com");
        props.put(
"mail.smtp.password""code");

        Session session 
= Session.getDefaultInstance(props, null);
        
try {
            Message msg 
= new MimeMessage(session);
            msg.setFrom(
new InternetAddress(SENDER_EMAIL_ADDRESS, SENDER_NAME));
            msg.setRecipient(Message.RecipientType.TO, 
new InternetAddress(
                    recipient));
            msg.setSubject(subject);
            msg.setSentDate(
new Date());
            msg.setText(message);
            Transport transport 
= session.getTransport("smtp");
            transport.connect((String) props.get(
"mail.smtp.host"), props
                    .getProperty(
"mail.smtp.user"), props
                    .getProperty(
"mail.smtp.password"));// 2
            transport.sendMessage(msg, msg.getAllRecipients());

        }
 catch (Exception e) {
            System.out.println(e);
        }


    }


    
public static void main(String[] args) {
        SendMainl sendMail 
= new SendMainl();
        sendMail.sendConfirmation();

    }

}