JavaEmail-发送email工具类

这是发送给单人的工具类

/**
 * @Description
 * @Author yuxiang
 * @CreatedDate 2019/9/10 2:26
 */
public class EmailUtil {

    /**
     * 发送邮件工具类
     * @param sender 发件人
     * @param recipient 收件人
     * @param emailSubject 邮件的主题
     * @param emailContent 邮件的内容
     * @return
     */
    public static int sendEmail(String sender,String recipient,
                                String emailSubject,String emailContent){
        int res=0;

        try {
            //跟smtp服务器建立一个连接
            Properties p = new Properties();
            //设置邮件服务器主机名 如 "smtp.qq.com"
            p.setProperty("mail.host","smtp.126.com");
            //发送服务器需要身份验证,要采用指定用户名密码的方式去认证
            p.setProperty("mail.smtp.auth", "true");
            //发送邮件协议名称
            p.setProperty("mail.transport.protocol", "smtp");

            //开启SSL加密,否则会失败
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            p.put("mail.smtp.ssl.enable", "true");
            p.put("mail.smtp.ssl.socketFactory", sf);

            // 创建session
            Session session = Session.getDefaultInstance(p, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    //第一个参数为邮箱账号,第二个为授权码
                    PasswordAuthentication pa = new PasswordAuthentication("idisStudio@126.com","idisstudio412");
                    return pa;
                }
            });

            //设置打开调试状态
//            session.setDebug(true);

            //可以发送几封邮件:可以在这里 for循环多次
            //声明一个Message对象(代表一封邮件),从session中创建
            MimeMessage msg = new MimeMessage(session);
            //邮件信息封装
            //1发件人
            msg.setFrom(new InternetAddress(sender));

            //一个的收件人
            msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(recipient));


            //3邮件内容:主题、内容
            msg.setSubject(emailSubject);
            //支持纯文本:"text/plain;charset=utf-8"
            msg.setContent(emailContent,"text/plain;charset=utf-8");
            //发送动作
            Transport.send(msg);
            System.out.println("邮件发送成功");
            res=1;

        } catch (Exception e) {
            System.out.println("邮件发送失败: "+e.getMessage());

            res=0;
        }
        return res;
    }
}
多种功能(转)
package com.test;
 
import java.util.Properties;
 
import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
 
import com.sun.mail.util.MailSSLSocketFactory;
 
public class JavaMailUtils {
	
	/**
	 * 发送邮件工具类:通过qq邮件发送,因为具有ssl加密,采用的是smtp协议
	 * @param mailServer 邮件服务器的主机名:如 "smtp.qq.com"
	 * @param loginAccount 登录邮箱的账号:如 "1974544863@qq.com"
	 * @param loginAuthCode 登录qq邮箱时候需要的授权码:可以进入qq邮箱,账号设置那里"生成授权码"
	 * @param sender 发件人
	 * @param recipients 收件人:支持群发
	 * @param emailSubject 邮件的主题
	 * @param emailContent 邮件的内容
	 * @param emailContentType 邮件内容的类型,支持纯文本:"text/plain;charset=utf-8";,带有Html格式的内容:"text/html;charset=utf-8" 
	 * @return
	 */
	public static int sendEmail(String mailServer,final String loginAccount,final String loginAuthCode,String sender,String[] recipients,
			String emailSubject,String emailContent,String emailContentType){
		int res=0;
		
	   try {
    	    //跟smtp服务器建立一个连接
            Properties p = new Properties();
            //设置邮件服务器主机名
            p.setProperty("mail.host",mailServer);
            //发送服务器需要身份验证,要采用指定用户名密码的方式去认证
            p.setProperty("mail.smtp.auth", "true");
            //发送邮件协议名称
            p.setProperty("mail.transport.protocol", "smtp");
 
            //开启SSL加密,否则会失败
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            p.put("mail.smtp.ssl.enable", "true");
            p.put("mail.smtp.ssl.socketFactory", sf);
 
            // 创建session
            Session session = Session.getDefaultInstance(p, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    //用户名可以用QQ账号也可以用邮箱的别名:第一个参数为邮箱账号,第二个为授权码
                    PasswordAuthentication pa = new PasswordAuthentication(loginAccount,loginAuthCode);
                    return pa;
                }
            });
 
            //设置打开调试状态
            session.setDebug(true);
 
        	//可以发送几封邮件:可以在这里 for循环多次
        	//声明一个Message对象(代表一封邮件),从session中创建
            MimeMessage msg = new MimeMessage(session);
            //邮件信息封装
            //1发件人
            msg.setFrom(new InternetAddress(sender));
            
            //2收件人:可以多个
            //一个的收件人
            //msg.setRecipient(RecipientType.TO, new InternetAddress("linsenzhong@126.com"));
            
            InternetAddress[] receptientsEmail=new InternetAddress[recipients.length];
            for(int i=0;i<recipients.length;i++){
            	receptientsEmail[i]=new InternetAddress(recipients[i]);
            }
            
            //多个收件人
            msg.setRecipients(RecipientType.TO,receptientsEmail);
            
            //3邮件内容:主题、内容
            msg.setSubject(emailSubject);
            //msg.setContent("Hello, 我是debug!!!", );//纯文本
            msg.setContent(emailContent,emailContentType);//发html格式的文本
            //发送动作
            Transport.send(msg);
            System.out.println("邮件发送成功");
            res=1;
            
		} catch (Exception e) {
			System.out.println("邮件发送失败: "+e.getMessage());
			
			res=0;
		}
		return res;
	}
	
    public static void main(String[] args) throws Exception {
    	
    	int res=sendEmail("smtp.qq.com", "这里输入你的qq邮箱", "这里输入前面说到的授权码", "发送人的qq邮箱", new String[]{
    			"1974544863@qq.com","linsenzhong@126.com" //这里就是一系列的收件人的邮箱了
    	}, "节日祝福", "祝你国庆节快乐,欢迎来我的blog: <a href='http://blog.csdn.net/u013871100'>我的blog</a>,祝您生活愉快!","text/html;charset=utf-8");
    	
    	System.out.println("\n发送结果:"+res);
    }
}
  • 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、付费专栏及课程。

余额充值