600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > 随笔之javamail邮件发送(阿里云企业邮箱)

随笔之javamail邮件发送(阿里云企业邮箱)

时间:2020-05-15 08:20:37

相关推荐

随笔之javamail邮件发送(阿里云企业邮箱)

mvn依赖:

<!-- Java Mail --><dependency><groupId>javax.mail</groupId><artifactId>javax.mail-api</artifactId></dependency><dependency><groupId>com.sun.mail</groupId><artifactId>javax.mail</artifactId><version>1.5.5</version></dependency><dependency><groupId>javax.activation</groupId><artifactId>activation</artifactId><version>1.1.1</version></dependency>

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;

import java.io.FileOutputStream;

import java.util.Properties;

public class Sendmail {

public static void main(String[] args) throws Exception {

Properties prop = new Properties();

prop.setProperty("mail.host", "");

prop.setProperty("mail.transport.protocol", "smtp");

prop.setProperty("mail.smtp.auth", "true");

//使用JavaMail发送邮件的5个步骤

//1、创建session

Session session = Session.getInstance(prop);

//开启Session的debug模式,这样就可以查看到程序发送Email的运行状态

session.setDebug(true);

//2、通过session得到transport对象

Transport ts = session.getTransport();

//3、连上邮件服务器

ts.connect("", "xxxxx", "xxxxxx");

//4、创建邮件

Message message = createMixedMail(session);

//5、发送邮件

ts.sendMessage(message, message.getAllRecipients());

ts.close();

}

public static MimeMessage createMixedMail(Session session) throws Exception {

//创建邮件

MimeMessage message = new MimeMessage(session);

//设置邮件的基本信息

message.setFrom(new InternetAddress("78028321@ifitting.me"));

message.setRecipient(Message.RecipientType.TO, new InternetAddress("78028321@"));

message.setSubject("带附件和带图片的的邮件");

//正文

MimeBodyPart text = new MimeBodyPart();

text.setContent("xxx这是女的xxxx<br/><img src='cid:aaa.jpg'>", "text/html;charset=UTF-8");

// //图片

// MimeBodyPart image = new MimeBodyPart();

// image.setDataHandler(new DataHandler(new FileDataSource("src\\3.jpg")));

// image.setContentID("aaa.jpg");

//

// //附件1

// MimeBodyPart attach = new MimeBodyPart();

// DataHandler dh = new DataHandler(new FileDataSource("src\\4.zip"));

// attach.setDataHandler(dh);

// attach.setFileName(dh.getName());

//描述关系:正文和图片

MimeMultipart mp1 = new MimeMultipart();

mp1.addBodyPart(text);

// mp1.addBodyPart(image);

mp1.setSubType("related");

//描述关系:正文和附件

MimeMultipart mp2 = new MimeMultipart();

// mp2.addBodyPart(attach);

//代表正文的bodypart

MimeBodyPart content = new MimeBodyPart();

content.setContent(mp1);

mp2.addBodyPart(content);

mp2.setSubType("mixed");

message.setContent(mp2);

message.saveChanges();

//message.writeTo(new FileOutputStream("E:\\MixedMail.eml"));

//返回创建好的的邮件

return message;

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。