java mail (there is text, pictures, there are accessories)

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/xinyuezitang/article/details/85768462

A demand:

1 java achieve mailing
2 sending content:
① text: captions and pictures
② Annex I: send pictures as an attachment
③ Annex II: Excel spreadsheet

Two ideas:

1 First, create a Java project, the download library join the project as a good javax.mail.jar
2 steps to create e-mail:
configuration parameters (SMTP mail server, whether SMTP authentication) connect mail server
to create a message object (MimeMessage)
Set the sender, the recipient (increased multiple recipients, Cc, Bcc)
setting message header, body, and other accessory
transmission time setting display

Three actions:

. (A) adding a dependency in pom.xml
example: add 1.4 version javax.mail, following FIG.

 <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4</version>
</dependency>

(B) Code

In the Controller layer

 /**
 * sendEmail  发邮件
 *   
 * @param to  参数to为收件人,只能为单个收件人
 * @return
 * @throws UnsupportedEncodingException
 * @throws MessagingException
 */
@RequestMapping(value = "/sendEmail",method = RequestMethod.GET)
public ResponseEntity<?> sendEmail( @RequestParam(value = "to") String to)
                                        throws UnsupportedEncodingException, MessagingException{
    topicService.sendMail(to);
    return Utility.ok();
}

In TopicService in:

/** The logger 日志. */
private Logger logger = LoggerFactory.getLogger(this.getClass());

 /**
 * sendMail 发邮件
 * 
 * @param to 收件人
 * @throws MessagingException 
 * @throws UnsupportedEncodingException 
 */
 public void sendMail(String to) throws UnsupportedEncodingException, MessagingException {

    //1.创建邮件对象
    Properties properties = new Properties();
    properties.put("mail.smtp.host", "smtp.51testing.com"); // 指定SMTP服务器
    properties.put("mail.smtp.auth", "true"); // 指定是否需要SMTP验证
    Session session = Session.getInstance(properties);
    MimeMessage message =new MimeMessage(session);

    //2.设置发件人
    // InternetAddress 的三个参数分别为: 邮箱, 显示的昵称(只用于显示, 没有特别的要求), 昵称的字符集编码
    message.setFrom(new InternetAddress("[email protected]","tang","UTF-8"));
    
    //3.设置收件人
    //To收件人   CC 抄送  BCC密送   
    message.setRecipient(MimeMessage.RecipientType.TO,new InternetAddress(to,"xin","UTF-8"));
   // message.addRecipient(MimeMessage.RecipientType.CC,new InternetAddress("409****[email protected]","xinyuezi","UTF-8"));

    //4.设置标题
    message.setSubject("测试邮件" ,"UTF-8");
    //message.setContent("Test Content:这是一封测试邮件...","text/html;charset=UTF-8");

    //5.设置邮件正文

    //一个Multipart对象包含一个或多个bodypart对象,组成邮件正文
    MimeMultipart multipart = new MimeMultipart();
    //读取本地图片,将图片数据添加到"节点"
    MimeBodyPart image = new MimeBodyPart();
    DataHandler dataHandler1 = new DataHandler(new FileDataSource("C:\\Users\\Public\\Pictures\\Sample Pictures\\flower.jpg"));
    image.setDataHandler(dataHandler1);
    image.setContentID("image_flower");

    //创建文本节点
    MimeBodyPart text = new MimeBodyPart();
    text.setContent("这张图片是花<br/><img src='cid:image_flower'/>","text/html;charset=UTF-8");

    //创建附件节点  读取本地文件,并读取附件名称
    MimeBodyPart file1 = new MimeBodyPart();
    DataHandler dataHandler2 = new DataHandler(new FileDataSource("C:\\Users\\Public\\Pictures\\Sample Pictures\\growing.png"));
    file1.setDataHandler(dataHandler2);
    file1.setFileName(MimeUtility.encodeText(dataHandler2.getName()));

    MimeBodyPart file2 = new MimeBodyPart();
    DataHandler dataHandler3 = new DataHandler(new FileDataSource("E:\\Tang\\topics.xlsx"));
    file2.setDataHandler(dataHandler3);
    file2.setFileName(MimeUtility.encodeText(dataHandler3.getName()));

    //将文本和图片添加到multipart
    multipart.addBodyPart(text);
    multipart.addBodyPart(image);
    multipart.addBodyPart(file1);
    multipart.addBodyPart(file2);
    multipart.setSubType("mixed");//混合关系

    message.setContent(multipart);

    message.setSentDate(new Date());
    message.saveChanges();
    Transport transport = session.getTransport("smtp");
    transport.connect("smtp.51testing.com","[email protected]","(需修改,填写自己的邮箱密码)");
    transport.sendMessage(message,message.getAllRecipients());
    transport.close();
    logger.info(Calendar.getInstance().getTime()+" : # Send mail to "+" success #");

    System.out.println("sendMail-----结束了");
}

(C) the results show
Here Insert Picture Description

Note: The parameters to this article only for a single recipient, is not suitable for mass mailings
but if you need to send multiple, multiple choice cc CC

Guess you like

Origin blog.csdn.net/xinyuezitang/article/details/85768462