import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
public class SendMailDemo1 {
public static void main(String[] args) throws Exception {
Properties props = new Properties();
//设置协议
props.setProperty("mail.transport.protocol", "smtp");
//设置服务器
props.setProperty("mail.host", "smtp.163.com");
//请求身份认证
props.setProperty("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("发件人邮箱"));//发件人
message.setRecipients(MimeMessage.RecipientType.TO, "收件人邮箱");//收件人
message.setSubject("这是一封java邮件");
MimeBodyPart textPart = new MimeBodyPart();
textPart.setContent("hello <img src='cid:map'/>world 这是一封java邮件", "text/html;charset=utf-8");
MimeBodyPart imagePart = new MimeBodyPart();
DataHandler dh = new DataHandler(new FileDataSource("F:/素材/地图.jpg"));
imagePart.setDataHandler(dh);
imagePart.setContentID("map");//设置cid
MimeMultipart mpart = new MimeMultipart();
mpart.addBodyPart(textPart);
mpart.addBodyPart(imagePart);
mpart.setSubType("related");//设置关系
MimeBodyPart textimagePart = new MimeBodyPart();
textimagePart.setContent(mpart);
//添加附件
MimeBodyPart attachmentPart = new MimeBodyPart();
dh = new DataHandler(new FileDataSource("C:/Users/Administrator/Desktop/计算机组成原理课件.zip"));
String fileName = dh.getName();//获取附件文件名,避免出现乱码
attachmentPart.setDataHandler(dh);
//手工设置附件名,注意编码问题
attachmentPart.setFileName(MimeUtility.encodeText(fileName));
MimeMultipart mpart2 = new MimeMultipart();
mpart2.addBodyPart(textimagePart);
mpart2.addBodyPart(attachmentPart);
mpart2.setSubType("mixed");//设置关系
message.setContent(mpart2);
message.saveChanges();//保存邮件改变
//发送邮件
Transport ts = session.getTransport();
ts.connect("用户名", "密码");//连接用户
ts.sendMessage(message, message.getAllRecipients());
ts.close();
}
}
javaMail 邮件发送带附件
最新推荐文章于 2022-12-08 21:37:37 发布