简易电子邮件发送程序!

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

/**
 *

Title:


 *

Description:


 *

Copyright: Copyright (c) 2004


 *

Company: Softek System


 * @author Softek System Development Team
 * @version 1.0
 */

public class SendMail {

  public static void main(String [] args){
    boolean is = new SendMail().sendMail("发件人地址","收件人地址","标题","信件内容");
   if(is)System.out.print("OK!");
   else System.out.print("Error!");

  }

  private String smtpHost ="smtp.163.com";
  public boolean sendMail(String fromAddress,String toAddress,String subject,String msgText){
     boolean isOk = false;
     smtpHost = "smtp.163.com";
    Properties props = new Properties();
    props.put("mail.smtp.host", smtpHost);
    Authen auth = new Authen();

    props.put("mail.smtp.auth", "true");
    Session session = Session.getDefaultInstance(props, auth);
    try{
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(fromAddress));
    InternetAddress [] address = {new InternetAddress(toAddress)};
    message.setRecipients(Message.RecipientType.TO, address);
    message.setSubject(subject); //设定主题
    message.setSentDate(new Date()); //设定发送时间
    message.setText(msgText); //把前面定义的msgText中的文字设定为邮件正文的内容
    Transport.send(message);
    isOk = true;
    }catch(MessagingException m) {
        //  System.out.println(m.toString());
    }
      return isOk;
  }
}
class Authen extends Authenticator {
  public PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication("用户名", "密码");
  }
}

你可能感兴趣的:(简易电子邮件发送程序!)