`

javamail 包含动态图片src cid:

阅读更多
首先配置spring的xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <bean id="mailsender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
           <property name="host">
            <value>smtp.163.com</value>
           </property>
           <property name="username">
            <value>youruser</value>
           </property>
           <property name="password">
            <value>yourpassword</value>
           </property>
        <property name="javaMailProperties">
            <props>
                 <prop key="mail.smtp.auth">true</prop>
             </props>
        </property>
     </bean>
    
    <bean id="mailmessage" class="org.springframework.mail.SimpleMailMessage">
           <property name="to">
            <value>youruser@163.com</value>
           </property>
           <property name="from">
            <value>youruser@163.com</value>
           </property>
           <property name="subject">
            <value>A sample mail</value>
           </property>
      </bean>
     
</beans>
邮件工厂,采用工厂模式: /** *//**
 * 
 */
package com.kevin.springmail;

import java.io.File;
import java.io.IOException;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.BasicConfigurator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.UrlResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

/** *//**
 * @author Administrator
 * @date   2006-9-15
 * @time   22:16:34
 */
public class MailFactory ...{
    
    private static final Log logger = LogFactory.getLog(MailFactory.class);
    private static final ApplicationContext context;
    /** *//**
     * 初始化beans
     */
    static ...{
        //加载log4j日志记录
        BasicConfigurator.configure();
        String springbean = "com/kevin/springmail/springmail.xml";
        context = new ClassPathXmlApplicationContext(springbean);
        logger.info("初始化beans springmail.xml 完成!");
    }
    
    /** *//**
     * 发送简单的邮件信息,邮件的内容都是纯文本的内容
     *
     */
    public static void sendSimpleMessageMail()...{
        
        SimpleMailMessage mailmessage = (SimpleMailMessage)context.getBean("mailmessage");
        JavaMailSenderImpl mailsender = (JavaMailSenderImpl)context.getBean("mailsender");
        
        mailmessage.setText("你好,Jarry!");
        mailsender.send(mailmessage);
        logger.info("simple mail has bean sent !");
    }
    
    /** *//**
     * 发送HTML格式的邮件,HTML格式中带有图片的,
     * 图片的来源是Server端的文件系统。(图片就是文件系统的)
     * @throws MessagingException
     * @throws IOException
     */
    public static void sendMimeMessageMail() throws MessagingException, IOException...{
        
        JavaMailSenderImpl mailsender = (JavaMailSenderImpl)context.getBean("mailsender");
        MimeMessage mimeMessage = mailsender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "GB2312");
        
        StringBuffer html = new StringBuffer();
        html.append("<html>");
        html.append("<head>");
        html.append("<meta http-equiv='Content-Type' content='text/html; charset=gb2312'>");
        html.append("</head>");
        html.append("<body bgcolor='#ccccff'>");
        html.append("<center>");
        html.append("<h1>你好,Jarry</h1>");
        html.append("<img src='cid:img'>");
        html.append("<p>logo:");
        html.append("<img src='cid:logo'>");
        html.append("</center>");
        html.append("</body>");
        html.append("</html>");
        
        helper.setText(html.toString(), true);
        
        FileSystemResource image = new FileSystemResource(new File("icon.gif"));
        helper.addInline("img",image);
        
        FileSystemResource logo = new FileSystemResource(new File("logo.gif"));
        helper.addInline("logo",logo);
        
        helper.setFrom("green006@163.com");
        helper.setTo("green006@163.com");
        helper.setSubject("spring javamail test");
        
        logger.info(mimeMessage.getContentID());
        logger.info(mimeMessage.getContent());
        
        
        mailsender.send(mimeMessage);
        logger.info("mime mail has bean sent !");
    }
    
    /** *//**
     * 发送带动态图象的HTML邮件,所谓动态图象就是在发送邮件时
     * 动态地生成一个图片,然后再随HTML格式的邮件发送出去。
     * @throws MessagingException 
     * @throws IOException 
     *
     */
    public static void sendDynamicImageMail() throws MessagingException, IOException...{
        
        JavaMailSenderImpl mailsender = (JavaMailSenderImpl)context.getBean("mailsender");
        MimeMessage mimeMessage = mailsender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "GB2312");
        
        StringBuffer html = new StringBuffer();
        html.append("<html>");
        html.append("<head>");
        html.append("<meta http-equiv='Content-Type' content='text/html; charset=gb2312'>");
        html.append("</head>");
        html.append("<body bgcolor='#ccccff'>");
        html.append("<center>");
        html.append("<h1>你好,Jarry</h1>");
        html.append("<img src='cid:png'>");//cid:png中的png就是下面的helper.addInline("png",image);中的png
        html.append("</body>");
        html.append("</html>");
        
        //设定邮件的正文内容
        helper.setText(html.toString(), true);
        
        //new一个UrlResource对象,注意http://localhost:8080/springtiles/makechart.png看起来好像一个png格式的
        //图片,其实makechart.png本质上是一个Servlet,在这个Servlet中用JFreeChart构造了一个3D的图象。
        UrlResource image = new UrlResource("http://localhost:8080/springtiles/makechart.png");
        
        //把生成的image图象添加到邮件信息中
        helper.addInline("png",image);
        
        helper.setFrom("green006@163.com");
        helper.setTo("green006@163.com");
        helper.setSubject("spring javamail test");
        
        logger.info(mimeMessage.getContentID());
        logger.info(mimeMessage.getContent());
        
        
        mailsender.send(mimeMessage);
        logger.info("dynamic image mail has bean sent !");
    }
    
    /** *//**
     *  发送带附件的电子邮件,包括文件名是中文的。
     *  (中文比较特殊些,不然会出现乱码)
     * 
     * @throws MessagingException
     * @throws IOException 
     */
    public static void sendMailWithAttachment() throws MessagingException, IOException...{
        
        JavaMailSenderImpl mailsender = (JavaMailSenderImpl)context.getBean("mailsender");
        MimeMessage mimeMessage = mailsender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "GB2312");
        
        StringBuffer html = new StringBuffer();
        html.append("<html>");
        html.append("<head>");
        html.append("<meta http-equiv='Content-Type' content='text/html; charset=gb2312'>");
        html.append("</head>");
        html.append("<body bgcolor='#ccccff'>");
        html.append("<center>");
        html.append("<h1>你好,Jarry</h1>");
        html.append("<p>logo:");
        html.append("<img src='cid:logo'>");
        html.append("</center>");
        html.append("</body>");
        html.append("</html>");
        
        helper.setText(html.toString(), true);
        
        FileSystemResource logo = new FileSystemResource(new File("logo.gif"));
        helper.addInline("logo",logo);
        
        //添加附件
        File file = new File("build.xml");
        helper.addAttachment("build.xml",file);
        
        //添加中文名的,不做下面的处理会出现乱码的。
        String filename = MimeUtility.encodeText(new String("个人助理-公元农历.mht".getBytes(),"GB2312"),"GB2312","B");
        File f = new File("个人助理-公元农历.mht");
        helper.addAttachment(filename,f);
        
        helper.setFrom("green006@163.com");
        helper.setTo("green006@163.com");
        helper.setSubject("spring javamail test");
        
        logger.info(mimeMessage.getContentID());
        logger.info(mimeMessage.getContent());
        
        
        mailsender.send(mimeMessage);
        logger.info("a mime mail with an attachment has bean sent !");
    }

}

生成3D图象的servlet: /** *//**
 * 
 */
package com.kevin.springmail;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.kevin.jfreechart.education.EducationAccount;

/** *//**
 * @author Administrator
 * @date   2006-9-16
 * @time   0:45:47
 */
public class ChartServlet extends HttpServlet ...{
    
    private final Log logger = LogFactory.getLog(this.getClass());
    
    /** *//**
     * 
     */
    private static final long serialVersionUID = 1L;
    
    private final String CONTENS_TYPE ="IMAGE/PNG";
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException ...{
        
        response.setContentType(CONTENS_TYPE);
        //利用JFreeChart构建生成3D的图表
        EducationAccount assetBar = new EducationAccount();
        assetBar.drawBar3D(response.getOutputStream());
        logger.info("完成在servlet中输出image!");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException ...{
        // TODO Auto-generated method stub
        doGet(request,response);
    }

    

}

简单测试一下: /** *//**
 * 
 */
package com.kevin.springmail;

import java.io.IOException;
import java.net.URISyntaxException;

import javax.mail.MessagingException;

/** *//**
 * @author Administrator
 * @date   2006-9-15
 * @time   22:36:29
 */
public class MailTest ...{

    /** *//**
     * @param args
     * @throws MessagingException 
     * @throws IOException 
     * @throws URISyntaxException 
     */
    public static void main(String[] args) throws MessagingException, IOException, URISyntaxException ...{
        // TODO Auto-generated method stub
        //MailFactory.sendSimpleMessageMail();
        //MailFactory.sendMimeMessageMail();
        MailFactory.sendMailWithAttachment();
    }

}
分享到:
评论

相关推荐

    利用JavaMail发送邮件示例

    在这个例子中,`image.jpg`是你要附加的图片文件,`&lt;img src="cid:image"&gt;`是HTML中的图片引用,`cid:image`与`imagePart`的`Content-ID`相匹配,使得邮件客户端能够正确显示图片。 总的来说,JavaMail是一个强大且...

    用java mail发送包含图片的html

    图片可以作为内联图片(`&lt;img&gt;`标签的`src`属性为`cid:`开头的唯一标识符),并且需要将图片转换为Base64编码并插入到HTML中。例如: ```html &lt;img src="cid:image1" alt="My Image"&gt; ``` 5. **创建...

    javamail:javamail 与 javamail 1.4

    textPart.setContent("&lt;html&gt;&lt;body&gt;&lt;img src=\"cid:image1\"&gt;&lt;/body&gt;&lt;/html&gt;", "text/html"); multipart.addBodyPart(textPart); MimeBodyPart imagePart = new MimeBodyPart(); imagePart.attachFile("image.jpg")...

    javamail学习

    &lt;/SPAN&gt;&lt;/SPAN&gt;&lt;/SPAN&gt;&lt;/SPAN&gt;&lt;/FONT&gt;" + "&lt;img src='cid:test1.jpg'&gt;"; Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipient(Message....

    用Java Mail发送带有图片的html格式的邮件.txt

    &lt;img src="cid:image1"&gt; ``` 这里的`image1`就是图片的cid,需要在MimeBodyPart中设置,以便在邮件客户端正确显示。 ### 四、代码示例 以下是一个简化的示例,展示了如何使用Java Mail API发送带有图片的HTML邮件...

    SpringBoot整合邮箱JavaMail

    String htmlContent = "&lt;html&gt;&lt;body&gt;&lt;h1&gt;这是邮件内容&lt;/h1&gt;&lt;img src=\"cid:image1\"&gt; &lt;p&gt;图片1&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;"; mailService.sendEmailWithImageAndAttachment("recipient@example.com", "邮件标题", ...

    JAVA 发送HTML格式并带图片的邮件实例

    `&lt;img&gt;`标签的`src`属性应设置为`cid:`加上之前设置的ID。 6. **设置邮件内容**: 将`Multipart`对象设置为`MimeMessage`的内容,使用`MimeMessage.setContent()`方法。 7. **发送邮件**: 最后,使用`Transport...

    JAVA使用EWS发送Exchange Mail 实例

    由于公司Exhange不让使用pop3和smtp,JAVAMAIL就不能用了,找了一下午还是测试成功了。 使用Eclipse3.6 JDK1.6开发,一个简单可运行的例子,包括了jar包。 更多详情请自行下载EWSJavaAPI研究

    spring整合freemarker发送邮件例子

    `&lt;img&gt;`标签中的`src`属性设置为`cid:image1`,表示图片内容将会内嵌到邮件中。 然后,我们需要创建一个Java类来处理邮件的发送逻辑。这个类通常会注入`JavaMailSender`和`FreemarkerTemplateEngine`,并提供一个...

    java发送邮件,可带图片

    String htmlContent = "&lt;html&gt;&lt;body&gt;&lt;img src=\"cid:image1\"&gt;&lt;/body&gt;&lt;/html&gt;"; MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(htmlContent, "text/html"); Multipart multipart = new ...

    可带附件的复杂邮件发送实例

    &lt;/span&gt;&lt;img src='cid:邮件主体的组合关系.jpg'&gt;", "text/html;charset=gbk"); htmlPart.addBodyPart(contBody); ``` 添加图片到HTML内容中,使用"MIME cid"(内容ID)引用,这样图片可以在邮件的HTML中正确显示: ...

    java mail源码

    例如,`&lt;img src="cid:image1"&gt;`,其中 `image1` 是在 `MimeBodyPart` 中设置的 `Content-ID`。 5. **接收邮件** 接收邮件通常涉及到使用 `Store` 和 `Folder` 对象。首先,建立 `Session` 并连接到邮件服务器,...

    Java发送邮件(包含jar包)

    textPart.setContent("&lt;html&gt;&lt;body&gt;&lt;h1&gt;Hello&lt;/h1&gt;&lt;img src=\"cid:image\"&gt;&lt;/body&gt;&lt;/html&gt;", "text/html"); mp.addBodyPart(textPart); BodyPart imagePart = new MimeBodyPart(); imagePart.attachFile("image.jpg...

    Spring邮件发送源码

    &lt;img src="cid:myImage" alt="图片描述" /&gt; ``` 在`Spring 邮件发送.doc`文档中,可能详细阐述了这些步骤,并提供了具体的示例代码。而`springmail.rar`可能包含了项目结构、配置文件和其他辅助资源,用于演示...

    Java email send image

    htmlPart.setContent("&lt;html&gt;&lt;body&gt;&lt;img src=\"cid:image\"&gt;&lt;/body&gt;&lt;/html&gt;", "text/html"); MimeBodyPart imagePart = new MimeBodyPart(); imagePart.setDataHandler(new DataHandler(new ByteArrayDataSource(new...

Global site tag (gtag.js) - Google Analytics