zoukankan      html  css  js  c++  java
  • JAVA中发送电子邮件的方法

       JAVA中发送邮件的方法不复杂,使用sun的JavaMail的架包就可以实现,也可以使用Spring Boot封装的方法,使用起来更加便捷。

     一、下载JavaMail的架包,并导入项目中,如下:

    如果是maven项目,maven依赖如下:

    1 <dependency>
    2     <groupId>com.sun.mail</groupId>
    3     <artifactId>javax.mail</artifactId>
    4     <version>1.5.6</version>
    5 </dependency>

    如果使用spring的方法,还需要导入以下maven依赖:

    1 <dependency>
    2     <groupId>org.springframework</groupId>
    3     <artifactId>spring-context-support</artifactId>
    4     <version>4.3.6.RELEASE</version>
    5 </dependency>

    二、使用JavaMail发邮件的代码例子,如下:

    1、在main函数中对各项参数进行赋值(参数说明已进行备注),即可通过send函数进行发送邮件操作。

     1 public class TestEmail {
     2 
     3     private final static String TIMEOUT_MS = "20000";
     4 
     5     public static void main(String[] args) {
     6         String host = "smtp.exmail.qq.com";
     7         String user = "xxxxxx@qq.com";
     8         String password = "xxxxxx";
     9         String recipients = "xxxxxx@qq.com";
    10         String cc = "";
    11         String subject = "邮件发送测试";
    12         String content = "邮件正文:<br>你好!";
    13         //方式1:通过URL获取附件
    14 //        byte[] attachment = FileUtil.getBytesByUrl("http://127.0.0.1/project/test.pdf");
    15         //方式2:通过本地路径获取附件
    16         byte[] attachment = FileUtil.getBytesByFile("c://fujian.pdf");
    17         
    18         String attachmentName = "";
    19         try {
    20             attachmentName = MimeUtility.encodeWord("这是附件.pdf");
    21             send(host, user, password, recipients, cc, subject, content, attachment, attachmentName);
    22         } catch (Exception e) {
    23             e.printStackTrace();
    24         }
    25     }
    26     
    27     /**
    28      * @param host 邮件服务器主机名
    29      * @param user 用户名
    30      * @param password 密码
    31      * @param recipients 收件人
    32      * @param cc 抄送人
    33      * @param subject 主题
    34      * @param content 内容
    35      * @param attachment 附件 [没有传 null]
    36      * @param attachmentName 附件名称 [没有传 null]
    37      * @throws Exception
    38      */
    39     public static void send(final String host, final String user, final String password,
    40                      final String recipients, final String cc, final String subject, final String content,
    41                      final byte[] attachment,final String attachmentName) throws Exception {
    42         Properties props = new Properties();
    43         props.put("mail.smtp.host", host);
    44         props.put("mail.smtp.auth", "true");
    45         props.put("mail.smtp.timeout", TIMEOUT_MS);
    46 
    47         Authenticator auth = new Authenticator() {
    48             @Override
    49             protected PasswordAuthentication getPasswordAuthentication() {
    50                 return new PasswordAuthentication(user, password);
    51             }
    52         };
    53         Session session = Session.getInstance(props, auth);
    54         MimeMessage msg = new MimeMessage(session);
    55         msg.setFrom(new InternetAddress(user));
    56         msg.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
    57         if (cc != null && cc.length() > 0) {
    58             msg.setRecipients(Message.RecipientType.CC, cc);
    59         }
    60         msg.setSubject(subject);
    61         // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
    62         Multipart multipart = new MimeMultipart();
    63         // 添加邮件正文
    64         BodyPart contentPart = new MimeBodyPart();
    65         contentPart.setContent(content, "text/html;charset=UTF-8");
    66         multipart.addBodyPart(contentPart);
    67         // 添加附件的内容
    68         if (attachment!=null) {
    69             BodyPart attachmentBodyPart = new MimeBodyPart();
    70             DataSource source = new ByteArrayDataSource(attachment,"application/octet-stream");
    71             attachmentBodyPart.setDataHandler(new DataHandler(source));
    72             //MimeUtility.encodeWord可以避免文件名乱码
    73             attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachmentName));
    74             multipart.addBodyPart(attachmentBodyPart);
    75         }
    76         // 将multipart对象放到message中
    77         msg.setContent(multipart);
    78         // 保存邮件
    79         msg.saveChanges();
    80         Transport.send(msg, msg.getAllRecipients());
    81     }
    82 }

    2、上面的例子中,如果有附件,可对附件进行设置。附件传参类型为byte数组,这里举2个例子,方式1通过网址获取byte数组,如下。方式2通过本地文件获取byte数组。具体可以查看另一篇文章:JAVA中文件与Byte数组相互转换的方法

     1 public class FileUtil {
     2 
     3     public static byte[] getBytesByUrl(String urlStr) {
     4         try {
     5             URL url = new URL(urlStr);
     6             HttpURLConnection conn = (HttpURLConnection) url.openConnection();
     7             InputStream is = conn.getInputStream();
     8             BufferedInputStream bis = new BufferedInputStream(is);
     9             ByteArrayOutputStream baos = new ByteArrayOutputStream();
    10             final int BUFFER_SIZE = 2048;
    11             final int EOF = -1;
    12             int c;
    13             byte[] buf = new byte[BUFFER_SIZE];
    14             while (true) {
    15                 c = bis.read(buf);
    16                 if (c == EOF)
    17                     break;
    18                 baos.write(buf, 0, c);
    19             }
    20             conn.disconnect();
    21             is.close();
    22 
    23             byte[] data = baos.toByteArray();
    24             baos.flush();
    25             return data;
    26 
    27         } catch (Exception e) {
    28             e.printStackTrace();
    29         }
    30         return null;
    31     }
    32 }

    2020-5-26 更新:

    三、使用Spring Boot发邮件的代码例子,如下:

     1 public class MailUtil {
     2 
     3     private static JavaMailSenderImpl javaMailSender;
     4 
     5     private static final String SENDER = "xxxxxx@qq.com";
     6 
     7     static {
     8         javaMailSender = new JavaMailSenderImpl();
     9         javaMailSender.setHost("smtp.qq.com");// 链接服务器
    10 //        javaMailSender.setPort(25);// 默认使用25端口发送
    11         javaMailSender.setUsername("xxxxxx@qq.com");// 邮箱账号
    12         javaMailSender.setPassword("xxxxxxxxxx");// 授权码
    13         javaMailSender.setDefaultEncoding("UTF-8");
    14 //        javaMailSender.setProtocol("smtp");
    15 
    16 //        Properties properties = new Properties();
    17 //        properties.setProperty("mail.debug", "true");// 启用调试
    18 //        properties.setProperty("mail.smtp.timeout", "1000");// 设置链接超时
    19 //        设置通过ssl协议使用465端口发送、使用默认端口(25)时下面三行不需要
    20 //        properties.setProperty("mail.smtp.auth", "true");// 开启认证
    21 //        properties.setProperty("mail.smtp.socketFactory.port", "465");// 设置ssl端口
    22 //        properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    23 
    24 //        javaMailSender.setJavaMailProperties(properties);
    25     }
    26 
    27     public static void main(String[] args) throws Exception {
    28         sendSimpleMail(new String[]{"xxxxxx@qq.com"}, "邮件主题", "邮件内容", false);
    29     }
    30 
    31     /**
    32      * 发送普通邮件
    33      *
    34      * @param to 收件人
    35      * @param subject 主题
    36      * @param text 正文
    37      * @param isHtml 正文是否为html格式
    38      */
    39     public static void sendSimpleMail(String[] to, String subject, String text, boolean isHtml) throws Exception {
    40         MimeMessage message = javaMailSender.createMimeMessage();
    41         MimeMessageHelper helper = new MimeMessageHelper(message, true);
    42         helper.setFrom(SENDER, "通知");
    43         helper.setTo(to);
    44         helper.setSubject(subject);
    45         helper.setText(text, isHtml);
    46         javaMailSender.send(message);
    47     }
    48 
    49     /**
    50      * 发送带附件邮件
    51      *
    52      * @param to 收件人
    53      * @param subject 主题
    54      * @param text 正文
    55      * @param files 附件
    56      */
    57     public static void sendAttachmentMail(String[] to, String subject, String text, Map<String, File> files) throws Exception {
    58         MimeMessage message = javaMailSender.createMimeMessage();
    59         MimeMessageHelper helper = new MimeMessageHelper(message, true);
    60         helper.setFrom(SENDER, "通知");
    61         helper.setTo(to);
    62         helper.setSubject(subject);
    63         helper.setText(text);
    64         Set<Map.Entry<String, File>> fileSet = files.entrySet();
    65         for (Map.Entry f : fileSet) {
    66             helper.addAttachment((String) f.getKey(), (File) f.getValue());
    67         }
    68         javaMailSender.send(message);
    69     }
    70 }

      注意12行的password不是你邮箱的登录密码,而是在邮箱中生成的授权码。获取授权码方法如下:

    登录QQ邮箱→设置→账户→POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务→开启“POP3/SMTP服务”,获取到一个授权码。

  • 相关阅读:
    高精度加法和减法。加法还好,减法花了不少时间。
    整数拆分
    二叉搜索树的中位数
    基本有序数组的排序
    log4j手册
    mysql技巧
    vim配置文件
    regex for python like preg_match of php
    字符串按word反转
    the little redis 阅读笔记
  • 原文地址:https://www.cnblogs.com/pcheng/p/6889133.html
Copyright © 2011-2022 走看看