javaMail发送邮件代码参考

java文件:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
 
/**
 * @see 该类用来发送qq邮件
 * @version 1.0
 * */
public class EmailTool implements Serializable {
     
    public static void main(String[] args) {
        try {
            /**只要你的电脑能上网,发件人账号密码地址都正确设置,这个邮件就绝对能发出去*/
            String email = "admin@163.com";// 收件人地址
            String title = "找回密码";// 邮件标题
            String url = "http://www.baidu.com";
            String img = "http://img1.kaixin001.com.cn/i/sy_tp1_1.gif";
            String templetPath = "D:\\test\\email\\findPass.txt";
            String []args1 = new String[]{ "洪秀全", "hongxiuquan", email, url, url, url, img };// 邮件模板的参数设置
            System.out.println(bean.sendEmail(email, title, templetPath, args1, templetPath));// 发送邮件
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    private static final long serialVersionUID = 1L;
    private static EmailTool bean = new EmailTool();
     
    /**
     * @see 以单例模式获得javabean
     * @return Email
     * */
    public static EmailTool getBean(){
        return bean;
    }
 
    /**
     * @see 用QQ邮箱发邮件
     * @param toEmail 收件人地址
     * @param title 邮件标题
     * @param templetPath 模板路径(物理路径)
     * @param args 模板中需要替换的值
     * @param affixPath 附件的路径(物理路径,可以为null)
     * @return boolean
     * */
    public Boolean sendEmail(String toEmail, String title, String templetPath,
            String []args, String affixPath) {
        Boolean result = false;
        try {
            Properties properties = new Properties();
            Session session = Session.getInstance(properties, null);
            properties.put("mail.smtp.host", emailServerIP);// 设置服务器的IP或域名
            properties.put("mail.smtp.auth", "true");// 允许smtp校验
            Transport transport = session.getTransport("smtp");
            transport.connect(emailServerIP, fromEmailAccount, fromEmailPassword);// 设置发件人的用户名和密码
            Message message = new MimeMessage(session);           
            message.setSubject(title);// 设置邮件主题
            Address address[] = { new InternetAddress(fromEmail) };// 改变发件人地址
            message.addFrom(address);
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));// 设置收件人地址           
            message.setSentDate(new Date());// 设置发送时间
            /**设置mail正文 ---begin*/ 
            String content = readTemplet(templetPath);// 读取邮件模板的内容
            for (int i = 0; i < args.length; i++) {
                content = content.replace("{" + i + "}", args[i]);// 替换模板中的占位符
            }
            MimeMultipart multipart = new MimeMultipart();
            MimeBodyPart contentPart = new MimeBodyPart();
            contentPart.setDataHandler(new DataHandler(content, "text/html;charset=gbk"));// 设置正文内容
            multipart.addBodyPart(contentPart);// 设置正文
            if (null != affixPath && !"".equals(affixPath)) {
                File file = new File(affixPath);
                if (file.exists() && !file.isDirectory() && file.length() <= affixFileSize) {// 附件必须在10M以下
                    MimeBodyPart affixPart = new MimeBodyPart();
                    affixPart.setDataHandler(new DataHandler(new FileDataSource(affixPath)));// 读取附件
                    affixPart.setFileName(MimeUtility.encodeText(file.getName()));//设置附件标题
                    multipart.addBodyPart(affixPart);// 设置附件
                }
            }
            message.setContent(multipart);
            /**设置mail正文---end*/ 
            message.saveChanges();// 保存发送信息
            transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));// 发送邮件
            transport.close();
            result = true;
        } catch (Exception e) {           
            e.printStackTrace();
        }
        return result;
    }
     
    // 读模板文件(换行符为\n)
    private String readTemplet(String templetPath) {
        if (!new File(templetPath).exists()) {
            return "";
        }
        try {
            InputStream input = new FileInputStream(templetPath);
            InputStreamReader read = new InputStreamReader(input, "UTF-8");
            BufferedReader reader = new BufferedReader(read);
            String line;
            String  result = "";
            while ((line = reader.readLine()) != null) {
                result += line + "\n";
            }
            reader.close();
            read.close();
            input.close();
            return result.substring(result.indexOf("<html>"));
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
     
    /**发件人的账号密码地址必须用你自己的,而且要开通smtp服务(打开你的qq邮箱点几下就行了)*/
    private String fromEmailAccount = "2457873910";// 发件人账号(qq号码)
    private String fromEmailPassword = "登录密码";// 发件人密码(qq密码)
    private String fromEmail = "2457873910@qq.com";// 发件人地址(qq邮箱)
    private Long affixFileSize = 1048576L * 10l;// 允许发送的最大附件大小(字节)
    private String emailServerIP = "smtp.qq.com";// 服务器的IP或域名
 
}

 注意:以上代码是读取文本的内容替换{0} ,其实可以从properties文件中读取内容并动态替换参数,如下

 

Locale locale = Locale.getDefault();
ResourceBundle bundle = ResourceBundle.getBundle("config/sign",locale);

String value = bundle.getString("test");
String format = MessageFormat.format(value,new Object[]{"北京","测试"});
System.out.println(format);
 对应资源内容为:test={0}测试{1}.

 

如果需要换行,则只需在需换行的位置加"\"。

注意:如果需要在资源文件中过滤"{}",则可以使用"'"包括,如'{}'。

资源文件:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<title>找回密码</title>
</head>
<body>
亲爱的用户 {0}:<br/>
  您好!我们是XXX系统的工作人员!<br/>
  感谢您对连锁门店管理系统的信赖和支持!<br/>
  您在连锁门店管理系统注册的用户名是:{1}<br/>
  您的邮箱地址是:{2}<br/>
  请<a href="{3}">点击</a>或复制这个网址去重新设置您的密码(24小时之内有效):<br/>
  <a href="{4}">{5}</a><br/>
  最后祝你生活愉快!
  <img src="{6}" border="0"/><br/>
</body>
</html>

 注意:邮件正文中不支持<script>,但可以加入样式,如下:

 

<style type="text/css">\
    table '{\
        border: 1px solid #B1CDE3;\
        border-collapse: collapse;\
    }'\
    td '{\
        border: 1px solid #B1CDE3;\
        font-size:28px;\
        text-align: center;\
        color: #4f6b72;\
    }'\
</style>\
注意:上面的{}用“‘”包括,是不被Properties解析,其中“\”是资源文件中换行连接符。

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值