备忘:Spring发送带附件的邮件(gmail,163)

备忘录:使用Spring发送各种类型的邮件,经测试,发送方和接收方可以是gmail,163。

 

当发送方是gmail时,设置有点不同。

 

Spring的设置:

 

	
	
	
	
	
	
		
		
		
		
			
				true
				25000
				465
				465
				false
				javax.net.ssl.SSLSocketFactory
			
		
	
	
	
	
		
		
		
	
	
	
	

 

 

上面的设置中,第一个JavaMailSender的发送方为163邮箱,后面的一个为gmail邮箱的。

 

下面是单元测试代码:

 

    private JavaMailSender mailSender;
    private MailMessage    mailMessage;
    private MimeMessage    mimeMessage;
    
    @Before
    public void setUp() {
        ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/spring/mail-context.xml");
        
        Assert.notNull(context);
        
        this.mailSender = context.getBean(JavaMailSender.class);
        this.mailMessage = context.getBean(MailMessage.class);
        this.mimeMessage = context.getBean(MimeMessage.class);
        
        Assert.notNull(this.mailSender);
        Assert.notNull(this.mailMessage);
        Assert.notNull(this.mimeMessage);
    }
    
    /**
     * 普通文本邮件
     */
    @Test
    public void testSendPlainTextMail() {
        this.mailMessage.setSubject("普通文本邮件");
        this.mailMessage.setText("测试Spring发送Email.");
        
        try {
            mailSender.send((SimpleMailMessage) this.mailMessage);
        } catch (MailException e) {
            System.out.println("Oops: 发送Email失败了....");
            e.printStackTrace();
        }
    }
    
    /**
     * HTML格式邮件
     * @throws MessagingException 
     */
    @Test
    public void testSendHTMLMail() throws MessagingException {
        MimeMessageHelper messageHelper = new MimeMessageHelper(this.mimeMessage, true, "UTF-8");
        
        messageHelper.setTo("[email protected]");
        messageHelper.setFrom("[email protected]");
        messageHelper.setSubject("HTML格式邮件");
        messageHelper.setText("

Hello! Spring!

XXX(中国)信息技术有限公司", true); this.mailSender.send(this.mimeMessage); } /** * 带附件的HTML格式邮件 * @throws MessagingException */ @Test public void testSetAttachMail() throws MessagingException { MimeMessageHelper messageHelper = new MimeMessageHelper(this.mimeMessage, true, "UTF-8"); messageHelper.setTo("[email protected]"); messageHelper.setFrom("[email protected]"); messageHelper.setSubject("带附件的HTML格式邮件"); messageHelper.setText("

Hello! Spring!

XXX(中国)信息技术有限公司", true); FileSystemResource file = new FileSystemResource(new File("E:/Study/Spring/Spring-Validator.jpg")); // 根据个人情况设置 messageHelper.addInline("SpringValidator", file); messageHelper.addAttachment("SpringValidator", file); ClassPathResource resource = new ClassPathResource("jbpm.cfg.xml"); // 根据个人情况设置 messageHelper.addInline("jbpm.cfg.xml", resource); messageHelper.addAttachment("jbpm.cfg.xml", resource); this.mailSender.send(this.mimeMessage); }

 

运行测试用例,即可看到结果!

 

你可能感兴趣的:(Spring)