热门关键字:  ubuntu  分区  函数  linux系统进程  Fedora

当前位置 :| 主页>Linux教程>编程开发>JAVA>

使用java发送email

来源: 作者: 时间:2008-05-30 Tag: 点击:
须下载sun公司的JavaMail API包,地址为:http://java.sun.com/products/javamail/ 并将相关包(jar文件)加到CLASSPATH中。
或者如果安装j2ee则将j2ee.jar加入classpath即可。
CODE:


import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
/**
*
Title: java mail

*
Description:

*
Copyright: Copyright (c) 2004

*
Company:

* @version 1.0
*/
public class SendMail
{
    public SendMail()
    {
    }
    public void send(){
        try
        {
            Properties props = new Properties();
            Session sendMailSession;
            Store store;
            Transport transport;
            props.put("mail.smtp.auth","true");
            props.put("mail.smtp.host", "smtp.yourmail.com"); //smtp主机名。
            props.put("mail.smtp.user","username@yourmail.com"); //发送方邮件地址。
            props.put("mail.smtp.password","888888"); //邮件密码。
            PopupAuthenticator popA=new PopupAuthenticator();//邮件安全认证。
            PasswordAuthentication pop = popA.performCheck("username","888888"); //填写用户名及密码
            sendMailSession = Session.getInstance(props, popA);
            Message newMessage = new MimeMessage(sendMailSession);
            newMessage.setFrom(new InternetAddress("username@yourmail.com"));
            newMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("receiver@mail.com"));  //接收方邮件地址
            newMessage.setSubject("邮件主题");
            newMessage.setSentDate(new Date());
            String mailContent;
            mailContent="你好!\n\n";
            mailContent+="\t邮件正文\n\n";
            mailContent+=new Date().toLocaleString();
            newMessage.setText(mailContent); //邮件正文
            transport = sendMailSession.getTransport("smtp");
            transport.send(newMessage);
        }
        catch (MessagingException ex)
        {
            ex.printStackTrace();
        }
    }
    public static void main(String[] args)
    {
        SendMail sml = new SendMail();
        sml.send();
    }
    public class PopupAuthenticator extends Authenticator{
        String username=null;
        String password=null;
        public PopupAuthenticator(){}
        public PasswordAuthentication performCheck(String user,String pass){
            username = user;
            password = pass;
            return getPasswordAuthentication();
        }
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    }
}

最新评论共有 0 位网友发表了评论
发表评论
评论内容:不能超过250字,需审核,请自觉遵守互联网相关政策法规。
用户名: 密码:
匿名?
注册
栏目列表