jsp+servlet实现javamail(3)

最后就是写可以实现邮件发送功能的JAVAMAIL函数了。注意把这个类放在和刚刚sevlet类的同一个包下面。 

package com.test;

import javax.mail.*;

import javax.mail.internet.*;

import java.util.*;

import java.util.Properties;

import javax.activation.*;

import javax.mail.Session;

import javax.mail.Multipart;

import javax.mail.internet.MimeBodyPart;

import javax.mail.internet.MimeUtility;

import java.util.Date;

public class sendmail

{

         static class SmtpAuth extends javax.mail.Authenticator

        {//这个函数是为了验证发件人的身份。你总不能随便写个发件地址也能发邮件给别人吧

          private String user,password;

          public void getuserinfo(String getuser,String getpassword)

          {

                    user = getuser;

                    password = getpassword;

        }

      protected javax.mail.PasswordAuthentication getPasswordAuthentication()

      {return new javax.mail.PasswordAuthentication(user,password);}           

   }

   public void send(String to,String chaosong,String subject,String content)

                          throws Exception,MessagingException

{//这个函数中带的参数值是在servlet中调用时传递过来的

            Properties props = new Properties();

           Session sendMailSession;

           Transport transport;

           SmtpAuth sa = new SmtpAuth();//用这个sa来进行验证和创建session

           sa.getuserinfo("xx"."xxxx");//输入发送方的用户名和密码

          sendMailSession = Session.getDefaultInstance(props,sa);

          transport = sendMailSession.getTransport("smtp");//使用smtp协议

         transport.connect("smtp.xxx.com","xxx","xxxx");//发件人的邮箱服务器,如smtp.sohu.com。用户名,密码

         props.put("mail.smtp.host","smtp.xxx.com");

         props.put("mail.smtp.auth","true");

         Message msg = new MimeMessage(sendMailSession);

       //建立新的邮件消息。

         msg.setSubject(subject);//设置邮件主题

        msg.setFrom(new InternetAddress(xx@xx.com));

        msg.setRecipient(Message.RecipientType.TO,new InternetAddress(to));

       if (chaosong ! ="")newMessage.setRecipient

                                       (Message.RecipientType.CC,new InternetAddress(chaosong));

       msg.setSentDate(new Date());

      msg.setText(content);

      transport.sendMessage(msg,msg.getAllRecipients());

}

     

       

        

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值