如何用JavaMail发邮件


这篇文章是要介绍如何要用JavaMail通过需认证的SMTP服务器发HTML格式的邮件。
首先在sun网站上下载JavaMail的实现,和JAF的实现(不知道为啥不放在一起),加入你的classpath。

代码先从Authenticator继承一个class,比如叫SMTPAuthenticator,这个要用于和SMTP服务器连接时做认证的。

 

ExpandedBlockStart.gif ContractedBlock.gif class  SMTPAuthenticator  extends  Authenticator  dot.gif {
InBlock.gif    
private String user;
InBlock.gif
InBlock.gif    
private String password;
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
public SMTPAuthenticator(String s, String s1) dot.gif{
InBlock.gif        user 
= s;
InBlock.gif        password 
= s1;
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
public PasswordAuthentication getPasswordAuthentication() dot.gif{
InBlock.gif        
return new PasswordAuthentication(user, password);
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedBlockEnd.gif}

 

然后开始发邮件,

 

None.gif     Session sendMailSession  =   null ;
None.gif    SMTPTransport transport 
=   null ;
None.gif    Properties props 
=   new  Properties();
None.gif
None.gif    
//  与服务器建立Session的参数设置
None.gif
    props.put( " mail.smtp.host " " smtp.163.com " );  //  写上你的SMTP服务器。
None.gif
    props.put( " mail.smtp.auth " " true " );  //  将这个参数设为true,让服务器进行认证。
None.gif
    SMTPAuthenticator auth  =   new  SMTPAuthenticator( " user " " mypassword " );  //  不用多说,用户名,密码。
None.gif

None.gif    sendMailSession 
=  Session.getInstance(props, auth);  //  建立连接。
None.gif    
//  SMTPTransport用来发送邮件。
None.gif
    transport  =  (SMTPTransport) sendMailSession.getTransport( " smtp " );
None.gif    transport.connect();
None.gif    
//  创建邮件。
None.gif
    Message newMessage  =   new  MimeMessage(sendMailSession);
None.gif    newMessage.setFrom(
new  InternetAddress( " me@163.com " ));
None.gif    newMessage.setRecipient(Message.RecipientType.TO, 
new  InternetAddress( " somebody@gmail.com " ));
None.gif    newMessage.setSubject(
" This a test mail for Java Mail API);
None.gif
    newMessage.setSentDate( new  Date());
None.gif    
None.gif    
//  使用MimeMultipart和MimeBodyPart才能发HTML格式邮件。
None.gif
    BodyPart bodyPart  =   new  MimeBodyPart();
None.gif    bodyPart.setContent(generateEmailBody(), 
" text/html;charset=gb2312 " );  //  发一个HTML格式的
None.gif
    Multipart mp  =   new  MimeMultipart();
None.gif    mp.addBodyPart(bodyPart);
None.gif    newMessage.setContent(mp);
None.gif
None.gif    Transport.send(newMessage);
None.gif

OK,邮件发出去啦~~

转载于:https://www.cnblogs.com/allenny/archive/2006/11/28/575597.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值