`

java发邮件

阅读更多
一、
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;


public class EmailUtil {
    public static void sendEmail(Object object){
        Properties props = new Properties();

//配置发邮件主机及SMTP
        props.setProperty("mail.host", "mail.china-ops.com");
        props.setProperty("mail.smtp.auth", "true");
        Authenticator authenticator = new Authenticator(){
            @Override
            public PasswordAuthentication getPasswordAuthentication() {

//发件人邮箱用户名和密码
                return new PasswordAuthentication("用户名","密码");
            }
        };
        Session session = Session.getDefaultInstance(props, authenticator);
        session.setDebug(true);
        
        Message message = new MimeMessage(session);
        
        try {

// 发件人
            message.setFrom(new InternetAddress("发件人邮箱"));

//收件人
            message.setRecipients(RecipientType.TO,InternetAddress.parse("接收者邮箱1,接收者邮箱2"));

//标题
            message.setSubject(ticket.getTicketType());

//内容
            String content = ""
                    + "您好:"
                    + ""
                    + "简要说明:"               
                    + ""
                    + ""+ dateToString(new Date(), "yyyy-MM-dd HH:mm:ss") + ""
                    + "";

            message.setContent(content,"text/html;charset=UTF-8");
            
            Transport.send(message);
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

     public Date stringToDate(String strTime, String formatType)
             throws Exception {
         SimpleDateFormat formatter = new SimpleDateFormat(formatType);
         Date date = null;
         date = formatter.parse(strTime);
         return date;
     }
}


二、
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.mail.internet.MimeMessage;

import org.apache.velocity.app.VelocityEngine;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.ui.velocity.VelocityEngineUtils;

/**
* Created with IntelliJ IDEA.
* 修改描述
*/
public class ActsocialMailSender {
   //从配置文件中读取相应的邮件配置属性
   private static final String emailHost = "smtp.126.com";
   private static final String userName = "sample@126.com";
   private static final String password = "password!";
   private static final String mailAuth = "true";
   private static Map<String, Object> proMap = null;
   private static JavaMailSenderImpl instance = null;
   private static VelocityEngine velocityEngine = null;

   static {
       proMap = new HashMap<String, Object>();
       proMap.put("resource.loader", "class");
       proMap.put("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");

   }

   public static JavaMailSender getInstance() {
       if (null == instance) {
           synchronized (JavaMailSenderImpl.class) {
               if (null == instance) {
                   instance = new JavaMailSenderImpl();
                   instance.setHost(emailHost);
                   instance.setUsername(userName);
                   instance.setPassword(password);
                   Properties properties = new Properties();
                   properties.setProperty("mail.smtp.auth", mailAuth);
                   //使用gmail发送邮件是必须设置如下参数的 主要是port不一样
                   if (emailHost.indexOf("smtp.gmail.com")>=0) {
                       properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                       properties.setProperty("mail.smtp.socketFactory.fallback", "false");
                       properties.setProperty("mail.smtp.port", "465");
                       properties.setProperty("mail.smtp.socketFactory.port", "465");
                   }
                   instance.setJavaMailProperties(properties);
               }
           }
       }

       return instance;
   }

   public static VelocityEngine getVelocityEngineInstance() {
       if (null == velocityEngine) {
           synchronized (VelocityEngine.class) {
               if (null == velocityEngine) {
                   velocityEngine = new VelocityEngine();
                   for (Map.Entry<String, Object> entry : proMap.entrySet()) {
                       velocityEngine.setProperty(entry.getKey(), entry.getValue());
                   }
               }
           }
       }
       return velocityEngine;
   }

   public static void sendEmail(final Map<String,Object> model,final String subject,final String vmfile,final String[] mailTo,final String [] files)
   {
       MimeMessagePreparator preparator = new MimeMessagePreparator() {
           //注意MimeMessagePreparator接口只有这一个回调函数
           public void prepare(MimeMessage mimeMessage) throws Exception
           {
               MimeMessageHelper message = new MimeMessageHelper(mimeMessage,true,"GBK");
               //这是一个生成Mime邮件简单工具,如果不使用GBK这个,中文会出现乱码
               //如果您使用的都是英文,那么可以使用MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
               message.setTo(mailTo);//设置接收方的email地址
               message.setSubject(subject);//设置邮件主题
               message.setFrom(userName);//设置发送方地址
               String text = VelocityEngineUtils.mergeTemplateIntoString(
                       ActsocialMailSender.getVelocityEngineInstance(), vmfile, "UTF-8", model);
               //从模板中加载要发送的内容,vmfile就是模板文件的名字
               //注意模板中有中文要加GBK,model中存放的是要替换模板中字段的值
//                text = "这是我自己定义的一个邮件模板邮件示例。";
               message.setText(text, true);
               //将发送的内容赋值给MimeMessageHelper,后面的true表示内容解析成html
               //如果您不想解析文本内容,可以使用false或者不添加这项
               FileSystemResource file;
               for(String s:files)//添加附件
               {
                   file = new FileSystemResource(new File(s));//读取附件
                   message.addAttachment(s, file);//向email中添加附件
               }
           }
       };
       ActsocialMailSender.getInstance().send(preparator);//发送邮件
   }

   public static void sendAlertEmail(final Map<String,Object> model,final String[] mailTo){
       sendEmail(model, "", "", mailTo, new String[]{});
   }
}

resources/welcom.vm
<html>
<body>
<h3>您好 $!{userName}, 欢迎您加入actsocial!</h3>
<div>
    您的email地址是<a href="mailto:${emailAddress}">$!{emailAddress}</a>.
    本条信息是系统自动发送,请勿回复!
</div>
<div style="text-align: right;">
    $!{inscribe}
    <br/>
    $!{date}
</div>
</body>
</html>


分享到:
评论

相关推荐

    java发邮件 java发email

    4. **创建Message对象**:`Message`对象代表邮件本身,使用`MimeMessage`类创建它,并设置发件人、收件人、主题和正文。例如: ```java MimeMessage message = new MimeMessage(session); message.setFrom(new ...

    java发邮件相关jar包

    在“java发邮件相关jar包”中,可能包含以下关键库: 1. **JavaMail API**: 这是Java用来处理邮件的核心库,包括`javax.mail`和`javax.mail.internet`这两个主要的包。它们提供了邮件协议(如SMTP、POP3、IMAP)的...

    java发邮件代码

    3. **创建Message对象**:使用Session对象创建一个Message实例,设置邮件的基本信息,如发件人、收件人、主题和正文。 ```java Message message = new MimeMessage(session); message.setFrom(new InternetAddress...

    java 发邮件例子

    以下是一个基于`commons-email-1.1`库的Java发邮件实例: 首先,确保你的项目已经正确地引入了`commons-email`库。这通常通过Maven或Gradle的依赖管理来完成。如果你使用的是Maven,可以在`pom.xml`文件中添加以下...

    java发邮件完整以及各个邮箱的设置

    JavaMail是Java编程语言中用于发送和接收电子邮件的标准API,它是通过JavaMail API来实现的。这个API提供了与SMTP(简单邮件传输协议)服务器交互的能力,使得开发者可以在应用程序中轻松地发送邮件。在这个主题中,...

    java发邮件用到的jar包

    在本例中,"java发邮件用到的jar包"指的是用于处理电子邮件的Java类库。下面将详细解释如何使用这些jar包以及相关的知识点。 首先,JavaMail API是Java中处理邮件的核心库,它提供了发送和接收电子邮件的接口。为了...

Global site tag (gtag.js) - Google Analytics