Java 发送带附件邮件

来源:互联网 发布:淘宝店 高峰后元数码 编辑:程序博客网 时间:2024/05/16 17:20

Java 发送邮件有两种实现方法。一种是通过JAVA MAIL jar包,还有一种办法是通过Spring Mail Api发送邮件。下面是详细代码:

Java Mail

需要 javax.mail jar包
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
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;

public class test {

public static void main(String[] args) throws UnsupportedEncodingException {    final String username = "发件人邮箱";    final String password = "邮箱密码";    final String host = "邮箱主机";    final String to =  "收件人邮箱";    Properties props = new Properties();    props.put("mail.smtp.auth", "true");    props.put("mail.smtp.ssl.enable", "true");//props.setProperty("mail.transport.protocol", "smtp");    //不做服务器证书校验    props.put("mail.smtp.ssl.checkserveridentity", "false");    //添加信任的服务器地址,多个地址之间用空格分开    props.put("mail.smtp.ssl.trust", "host");    props.put("mail.smtp.host", "host");    props.put("mail.smtp.port", "25");     // SMTP邮件服务器默认端口,默认为25    Session session = Session.getInstance(props,            new javax.mail.Authenticator() {

protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(username, password);
}
});

    try {        session.setDebug(true);        Message message = new MimeMessage(session);        message.setFrom(new InternetAddress(username));        message.setRecipient(Message.RecipientType.TO,                new InternetAddress(to));

// message.setRecipient(Message.RecipientType.CC,
// new InternetAddress(“另一个人的邮箱”));
message.setSubject(“Email Testing Subject”);
//添加附件
Multipart multipart = new MimeMultipart();
BodyPart part = new MimeBodyPart();
part.setContent(“你好啊!”, “text/html;charset=UTF-8”);
multipart.addBodyPart(part);

         BodyPart part2 = new MimeBodyPart();           DataSource dataSource = new FileDataSource("附件的绝对路径,记得分隔符是 //");           DataHandler dataHandler = new DataHandler(dataSource);           // 得到附件本身并至入BodyPart           part2.setDataHandler(dataHandler);           part2.setFileName(MimeUtility.encodeText(dataSource.getName()));           multipart.addBodyPart(part2);           message.setContent(multipart);        System.out.println("start");        Transport.send(message);        System.out.println("end");    } catch (MessagingException e) {        throw new RuntimeException(e);    }}

}

Spring mail jar包发送邮件

需要导入 Spring core 包和Spring bens包和Spring aop包
import java.io.File;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

public class test2 {

/**  * 本类测试简单邮件 直接用邮件发送  *   * @Author Li  * @throws MessagingException  *   */      public static void main(String args[]) throws MessagingException    {          JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();          // 设定mail server          senderImpl.setHost("邮箱服务器");         /*         * // 建立邮件消息              SimpleMailMessage mailMessage = new SimpleMailMessage();          */        // 建立邮件消息,发送简单邮件和html邮件的区别          MimeMessage mailMessage = senderImpl.createMimeMessage();          MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true);          /*        //建立邮件信息 带附件的        // 注意这里的boolean,等于真的时候才能嵌套图片,在构建MimeMessageHelper时候,所给定的值是true表示启用,          // multipart模式 为true时发送附件 可以设置html格式          MimeMessage mailMessage = senderImpl.createMimeMessage();         MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,                  true, "utf-8");        */        // 设置收件人,寄件人 用数组发送多个邮件          // String[] array = new String[] {"sun111@163.com","sun222@sohu.com"};          // mailMessage.setTo(array);          messageHelper.setTo("收件人邮箱");    // 设置收件人        messageHelper.setFrom("发件人邮箱");  // 设置发件人        messageHelper.setSubject(" 测试邮件发送! ");      // 设置主题        /*        //简单文件的文本        messageHelper.setText(" 测试我的简单邮件发送机制!! ");           */        //html邮件的文本

// messageHelper.setText(“

hello!!spring html Mail

“,
// true);
//html 带图片的文本
messageHelper.setText(

hello!!spring image html mail


+ ““, true);

        FileSystemResource img = new FileSystemResource(new File("e:/123.jpg"));          messageHelper.addInline("aaa", img);          /*        // 带附件的文本        messageHelper.setText(                  "<html><head></head><body><h1>你好:附件中有学习资料!</h1></body></html>",                  true);          FileSystemResource file = new FileSystemResource(new File("e:/test.rar"));          // 这里的方法调用和插入图片是不同的。          messageHelper.addAttachment("test.rar", file);          */        senderImpl.setUsername("用户账号");          senderImpl.setPassword("用户密码");        Properties prop = new Properties();          // 将这个参数设为true,让服务器进行认证,认证用户名和密码是否正确          prop.put(" mail.smtp.auth ", " true ");       //Socket I/O timeout value in milliseconds. Default is infinite timeout.        prop.put(" mail.smtp.timeout ", " 25000 ");       //If set to true, use SSL to connect and use the SSL port by default.       //Defaults to false for the "smtp" protocol and true for the "smtps" protocol.        prop.put("mail.smtp.ssl.enable", "true");     // SMTP邮件服务器默认端口,默认为25        prop.put("mail.smtp.port", "25");       //If set to true, checks the server identity as specified by RFC 2595. Defaults to false.        prop.put("mail.smtp.ssl.checkserveridentity", "false");     //If set, and a socket factory hasn't been specified, enables use of a MailSSLSocketFactory.      //If set to "*", all hosts are trusted.      //If set to a whitespace separated list of hosts, those hosts are trusted.      //Otherwise, trust depends on the certificate the server presents.        prop.put("mail.smtp.ssl.trust", "邮箱服务器");        senderImpl.setJavaMailProperties(prop);          // 发送邮件          try {            System.out.println("发送邮件");            senderImpl.send(mailMessage);        } catch (MailException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }          System.out.println(" 邮件发送成功.. ");      }  }  
0 0