/* 生成邮件 */ public class JavaMail3 { public static void main(String[] args) throws Exception { Session session=Session.getInstance(new Properties() ); MimeMessage msg=new MimeMessage(session); msg.setFrom(new InternetAddress("\""+MimeUtility.encodeText("小勇")+"\"","369631393@qq.com")); // msg.setFrom(new InternetAddress("369631393@qq.com")); msg.setSubject("你们的java培训真的是最牛的吗?"); msg.setReplyTo(new Address[]{new InternetAddress("out369631393@163.com")});//回复给某人 msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(MimeUtility.encodeText("小勇")+"<out369631393@126.com>,"+MimeUtility.encodeText("小能")+"<out369631393@sohu.com>")); MimeMultipart msgMultipart=new MimeMultipart("mixed"); msg.setContent(msgMultipart); MimeBodyPart content=new MimeBodyPart(); MimeBodyPart attch1=new MimeBodyPart(); MimeBodyPart attch2=new MimeBodyPart(); msgMultipart.addBodyPart(attch1); msgMultipart.addBodyPart(attch2); msgMultipart.addBodyPart(content); //附件1 DataSource ds1=new FileDataSource("C:\\Users\\Administrator\\Desktop\\fd.txt"); DataHandler dh1=new DataHandler(ds1); attch1.setDataHandler(dh1); attch1.setFileName( MimeUtility.encodeText("java培训.txt") ); //附件2 DataSource ds2=new FileDataSource("C:\\Users\\Administrator\\Desktop\\gq.jpg"); DataHandler dh2=new DataHandler(ds2); attch2.setDataHandler(dh2); attch2.setFileName("gq.jpg"); //正文内容 MimeMultipart bodyMultipart=new MimeMultipart("related"); content.setContent(bodyMultipart);//把正文体加入content去 MimeBodyPart htmlPart=new MimeBodyPart(); MimeBodyPart gifPart=new MimeBodyPart(); bodyMultipart.addBodyPart(htmlPart); bodyMultipart.addBodyPart(gifPart); //在正文中插入图片 DataSource gifds=new FileDataSource("C:\\Users\\Administrator\\Desktop\\gq.jpg"); DataHandler gifdh=new DataHandler(gifds); gifPart.setDataHandler(gifdh); //该图片显示在头部,如果没网络的时候,下面那网络连接的图片将用上面的gq.jpg代替 gifPart.setHeader("Content-Location","https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1572106018410&di=9a46b15714679cab06ef3b06384e5535&imgtype=0&src=http%3A%2F%2Fimage.zhangxinxu.com%2Fimage%2Fblog%2F201808%2Fjs-base64-thumb.jpg"); //插入html文本 htmlPart.setContent("你们的java培训真的是最牛的吗?大家都这么说,我想跟你们比试一下,这可是我自己用程序生成和发送的邮件哦!<img src='https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1572106018410&di=9a46b15714679cab06ef3b06384e5535&imgtype=0&src=http%3A%2F%2Fimage.zhangxinxu.com%2Fimage%2Fblog%2F201808%2Fjs-base64-thumb.jpg'>","text/html;charset=gbk"); //把这个对象生成复杂的文本 msg.saveChanges(); OutputStream ips=new FileOutputStream("C:\\Users\\Administrator\\Desktop\\email.eml"); msg.writeTo(ips); ips.close(); //发送 // Transport.send(msg);//静态方法 } }
生成邮件
最新推荐文章于 2024-06-23 09:36:15 发布