这里写的是一个复杂的邮件,里面包含附件和图片(注意看红色的字体)
源代码:
public static void main(String[] args) {
//Properties:配置文件,
Properties properties = new Properties();
//设置QQ邮箱服务器进行ssl验证
properties.setProperty("mail.smtp.ssl.enable", "true");
//QQ邮箱发送的协议为stmp
properties.setProperty("mail.transport.protocol", "smtp");
Session session = Session.getInstance(properties);
session.setDebug(true);
//Message:创建和解析邮件内容
Message msg = new MimeMessage(session);
try {
//设置发送者的信息
msg.setFrom(new InternetAddress("392016423@qq.com"));
//设置显示邮件的标题名称为‘你最尊敬的大佬’
msg.setFrom(new InternetAddress("\""+ MimeUtility.encodeText("你最尊敬的大佬") +"\"<392016423@qq.com> "));
} catch (MessagingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//指明整个邮件的架构,包括正文和附件
MimeMultipart msgMultipart = new MimeMultipart("mixed");
try {
//构造整个邮件的架构
msg.setContent(msgMultipart);
MimeBodyPart attch1 = new MimeBodyPart(); //邮件的附件
MimeBodyPart attch2 = new MimeBodyPart(); //邮件的附件
MimeBodyPart content = new MimeBodyPart(); //邮件的正文
****//注意在这里必须设置每一个MimeBodyPart 类对象的context,不然就会报no mimebodypart content****
attch1.setContent("", "text/html;charset=UTF-8");
attch2.setContent("", "text/html;charset=UTF-8");
//将各个组成部分组合在一起
msgMultipart.addBodyPart(attch1);
msgMultipart.addBodyPart(attch2);
msgMultipart.addBodyPart(content);
//对邮件的附件进行细节处理
DataSource ds1 = new FileDataSource("");
DataHandler dh1 = new DataHandler(ds1);
attch1.setDataHandler(dh1);
try {
//对附件进行设置中文名字:用MimeUtility类的encodeText(String str)方法
attch2.setFileName( MimeUtility.encodeText(""));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DataSource ds2 = new FileDataSource("");
DataHandler dh2 = new DataHandler(ds2);
attch1.setDataHandler(dh2); //DataHandler()方法:进行数据包装
//对邮件的正文部分进行处理
//MimeMultipart bodyMultipart = new MimeMultipart("multipart/related");
//QQ邮箱使用下面这种方式
MimeMultipart bodyMultipart = new MimeMultipart("related");
content.setContent(bodyMultipart);//注意这儿也是不可缺少
MimeBodyPart htmlBodyPart = new MimeBodyPart();//
MimeBodyPart gtfBodyPart = new MimeBodyPart();//图片
gtfBodyPart.setContent("哈哈哈!", "text/html;charset=UTF-8");
htmlBodyPart.setContent("我只是想来测试一下。。。。。。。。。", "text/html;charset=utf-8");
bodyMultipart.addBodyPart(gtfBodyPart);
bodyMultipart.addBodyPart(htmlBodyPart);
DataSource gtfds = new FileDataSource("1.jpg");
DataHandler gtfdh = new DataHandler(gtfds);
gtfBodyPart.setDataHandler(gtfdh);
msg.saveChanges();
//transport用于发送
Transport transport = session.getTransport();
//建立连接,QQ邮箱服务器地址smtp.qq.com,端口号:465,
//你的账户382816843@qq.com,
//注意ntulsxbdknfkbjej为授权码,并不是密码
transport.connect("smtp.qq.com",465, "382816843@qq.com", "ntulsxbdknfkbjej");
//设置接受方邮件的地址
transport.sendMessage(msg, new Address[]{new InternetAddress("3601905481@qq.com")});
transport.close();//最后记得关闭连接
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}