代码:
package com.dai.mail; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Message; 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; public class HtmlMessageSender { String protocol = "smtp"; String from = "15829004147@sina.cn"; String to = "243047007@qq.com"; String subject = "test"; String body = " " + "welcome to our website!" + "this is a test mail from sina!"; /** * create session and the session has been setted particular properties * @return */ public Session createSession() { Properties props = new Properties(); props.setProperty("mail.transport.protocol", protocol); /*必须将mail.smtp.auth属性设置为true,SMTPTransport对象才会向SMTP服务器提交认证 * 信息,这个信息可以从JavaMail的javadocs文档中的com.sun.mail.smtp包的帮助文档中 * 看到*/ props.setProperty("mail.smtp.auth", "true"); Session session = Session.getInstance(props); session.setDebug(true); return session; } /** * create MimeMessage,used the MultiBodyPart and MimeBodyPart * @param session * @return * @throws Exception */ public MimeMessage createMessage(Session session) throws Exception { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); message.setSubject(subject); MimeMultipart multiPart = new MimeMultipart("related"); MimeBodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setContent(body,"text/html;charset = GBK"); multiPart.addBodyPart(htmlBodyPart); MimeBodyPart gifBodyPart = new MimeBodyPart(); FileDataSource fds = new FileDataSource("d://zzz//love.jpg"); gifBodyPart.setDataHandler(new DataHandler(fds)); gifBodyPart.setContentID("love_jpg"); multiPart.addBodyPart(gifBodyPart); message.setContent(multiPart); message.saveChanges(); return message; } public static void main(String[] args) throws Exception { String server = "smtp.sina.com.cn"; String user = "15829004147@sina.cn"; String pass = "XXX";//密码 HtmlMessageSender sender = new HtmlMessageSender(); Session session = sender.createSession(); MimeMessage message = sender.createMessage(session); //获取Transport对象,并连接邮件服务器发送邮件 Transport transport = session.getTransport(); transport.connect(server, user, pass); transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO)); transport.close(); } }