【SSH网上商城项目实战25】使用java email给用户发送邮件

  当用户购买完商品后,我们应该向用户发送一封邮件,告诉他订单已生成之类的信息,邮箱地址是从用户的基本信息中获取,好了,首先我们来看一下Java中发送邮件的方法。

1. java中发送email的方法

  在完善这个项目之前,先来回顾一下java中是如何发送邮件的,首先肯定需要发送邮件的jar包:mail.jar,导入到lib目录下,好了,下面我们先写一个普通的java程序来回顾一下Java email的知识点:

public class SendEmailDemo {

    public static void main(String[] args) throws Exception {

        //1. 登陆邮件客户端(创建会话session)
        Properties prop = new Properties();
        prop.setProperty("mail.transport.protocol", "smtp");    
        //创建了session会话
        Session session = Session.getDefaultInstance(prop);
        //设置debug模式来调试发送信息
        session.setDebug(true);
        //创建一封邮件对象
        Message message = new MimeMessage(session);
        //写信
        message.setSubject("欢迎访问我的CSDN博客主页!");
        //正文内容
        message.setContent("欢迎访问我的CSDN博客主页:http://blog.csdn.net/eson_15"
                + ",么么哒~", "text/html;charset=utf-8");
        //附件人地址
        message.setFrom(new InternetAddress("nishengwus@163.com"));
        Transport transport = session.getTransport();
        //链接邮件服务器的认证信息
        transport.connect("smtp.163.com", "nishengwus", "xxxxx密码");
        // 设置收件人地址,并发送邮件
        transport.sendMessage(message, new InternetAddress[]{new InternetAddress("694076359@qq.com")});
        transport.close();
    }
}
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

  上面就是用java发送邮件的流程:创建会话–>封装邮件信息–>设置发件人地址–>设置收件人地址–>发送。

2. 封装发送邮件功能

  回顾了java发送邮件的方法后,我们将这个流程封装到一个工具类中,新建一个EmailUtilImpl实现类,完成后 抽取成EmailUtil接口,如下:

//抽取后的EmailUtil接口
public interface EmailUtil {

    public abstract void sendEmail(String emailAddress, String id);

}

//EmailUtilImpl实现类
@Component("emailUtil")
public class EmailUtilImpl implements EmailUtil {
    //参数接收顾客的邮箱地址和订单编号
    @Override
    public void sendEmail(String emailAddress, String id) {
        // 1. 登陆邮件客户端(创建会话session)
        Properties prop = new Properties();
        Session session = null;
        Message message = null;
        Transport transport = null;
        try {
            prop.setProperty("mail.transport.protocol", "smtp");
            // 创建了session会话
            session = Session.getDefaultInstance(prop);
            // 设置debug模式来调试发送信息
            session.setDebug(true);
            // 创建一封邮件对象
            message = new MimeMessage(session);
            // 写信
            message.setSubject("网上商城订单反馈");
            // 正文内容
            message.setContent("顾客您好,欢迎您光顾网上商城,订单" + id + "已支付成功!", "text/html;charset=utf-8");
            // 附件人地址
            message.setFrom(new InternetAddress("soft03_test@sina.com"));           
            transport = session.getTransport();
            // 链接邮件服务器的认证信息
            transport.connect("smtp.sina.com", "soft03_test", "soft03_test");

            // 设置收件人地址,并发送邮件
            transport.sendMessage(message, new InternetAddress[] { new InternetAddress(emailAddress) });
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {         
            try {
                transport.close();
            } catch (MessagingException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    }
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50

3. 完善payAction

  完成了工具类的封装,接下来我们把该工具类放到BaseAction中,通过@Resource注解注入进来,供Action使用,下面我们完善前面的payAction中的backBank()方法,如下:

@Controller("payAction")
@Scope("prototype")
public class PayAction extends BaseAction<Object> implements ParameterAware {

    //省略不相关的代码……

    public void backBank() {
        BackData backData = (BackData)model;
        System.out.println(model);
        boolean isOK = payService.checkBackData(backData);
        if(isOK) {
            //1. 更新订单状态,参数是自己根据数据库中的情况传进去的,用来测试
            forderService.updateStatusById(Integer.valueOf(201605006), 2);
            //2. 根据user邮箱地址,发送邮件
            String emailAddress = backData.getR8_MP().split(",")[0];
            emailUtil.sendEmail(emailAddress, backData.getR6_Order());
            //3. 发送手机短信,下一篇博客来介绍发送短信的功能
            System.out.println("----success!!----");
        } else {
            System.out.println("----false!!!----");
        }
    }
}
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

  从易宝那边返回的信息中r6_Order参数中保存的是订单的编号,r8_MP参数中是用户的邮箱和电话,第一个是邮箱第二个是电话,用逗号隔开了,所以我们首先要获取用户的邮箱地址,然后再来发送邮件。好了,支付完成后给用户发送邮件的功能就完成了。

  相关阅读:http://blog.csdn.net/column/details/str2hiberspring.html
  整个项目的源码下载地址:http://blog.csdn.net/eson_15/article/details/51479994


—–乐于分享,共同进步!
—–更多文章请看:http://blog.csdn.net/eson_15

(function () {('pre.prettyprint code').each(function () { var lines = (this).text().split(\n).length;var numbering = $('
    ').addClass('pre-numbering').hide(); (this).addClass(hasnumbering).parent().append( numbering); for (i = 1; i
    • 0
      点赞
    • 0
      收藏
      觉得还不错? 一键收藏
    • 0
      评论
    /* * JCatalog Project */ package com.hexiang.utils; import java.util.List; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.Properties; import javax.mail.Session; import javax.mail.Transport; import javax.mail.Message; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.hexiang.exception.CatalogException; /** * Utility class to send email. * * @author <a href="380595305@qq.com">hexiang</a> */ public class EmailUtil { //the logger for this class private static Log logger = LogFactory.getLog("com.hexiang.util.EmailUtil"); /** * Send email to a single recipient. * * @param smtpHost the SMTP email server address * @param senderAddress the sender email address * @param senderName the sender name * @param receiverAddress the recipient email address * @param sub the subject of the email * @param msg the message content of the email */ public static void sendEmail(String smtpHost, String senderAddress, String senderName, String receiverAddress, String sub, String msg) throws CatalogException { List<String> recipients = new ArrayList<String>(); recipients.add(receiverAddress); sendEmail(smtpHost, senderAddress, senderName, recipients, sub, msg); } /** * Send email to a list of recipients. * * @param smtpHost the SMTP email server address * @param senderAddress the sender email address * @param senderName the sender name * @param recipients a list of receipients email addresses * @param sub the subject of the email * @param msg the message content of the email */ public static void sendEmail(String smtpHost, String senderAddress, String senderName, List<String> recipients, String sub, String msg) throws CatalogException { if (smtpHost == null) { String errMsg = "Could not send email: smtp host address is null"; logger.error(errMsg); throw new CatalogException(errMsg); } try { Properties props = System.getProperties(); props.put("mail.smtp.host", smtpHost); Session session = Session.getDefaultInstance(props, null ); MimeMessage message = new MimeMessage( session ); message.addHeader("Content-type", "text/plain"); message.setSubject(sub); message.setFrom(new InternetAddress(senderAddress, senderName)); for (Iterator<String> it = recipients.iterator(); it.hasNext();) { String email = (String)it.next(); message.addRecipients(Message.RecipientType.TO, email); } message.setText(msg); message.setSentDate( new Date() ); Transport.send(message); } catch (Exception e) { String errorMsg = "Could not send email"; logger.error(errorMsg, e); throw new CatalogException("errorMsg", e); } } }
    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

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

    抵扣说明:

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

    余额充值