应用java mail和阿里云发送邮件和上传附件

来源:互联网 发布:linux 开启snmp 编辑:程序博客网 时间:2024/05/19 13:05
package com.mail;

import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
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 SendMail {

public static void main(String[] args) throws MessagingException, UnsupportedEncodingException {
Properties prop=new Properties();
prop.put("mail.host","smtp.aliyun.com" );
prop.put("mail.transport.protocol", "smtp");
prop.put("mail.smtp.auth", "true");
Session session=Session.getInstance(prop);
session.setDebug(true);
Transport ts=session.getTransport();
ts.connect("qinxin0823@aliyun.com", "123456"); //登录的账户名 和 密码
Message msg=createSimpleMail(session);
ts.sendMessage(msg, msg.getAllRecipients());
}
public static MimeMessage createSimpleMail(Session session) throws AddressException,MessagingException, UnsupportedEncodingException{
MimeMessage mm=new MimeMessage(session);
mm.setFrom(new InternetAddress("qinxin0823@aliyun.com")); //设置发件人
mm.setRecipient(Message.RecipientType.TO, new InternetAddress("274788664@qq.com")); //设置收件人
//mm.setRecipient(Message.RecipientType.CC, new InternetAddress("XXXX@qq.com")); //设置抄送人
mm.setSubject("清算清单!");
Multipart multipart = new MimeMultipart();
String mailBody = "请查收";
BodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent(mailBody, "text/html;charset=utf-8");
multipart.addBodyPart(bodyPart);
BodyPart bodyPart1 = new MimeBodyPart();
FileDataSource fileDataSource = new FileDataSource("c:/投资(或清算)总表.xlsx");
bodyPart1.setDataHandler(new DataHandler(fileDataSource));
bodyPart1.setFileName(MimeUtility.encodeText(fileDataSource.getName()));
multipart.addBodyPart(bodyPart1);
mm.setContent(multipart);
mm.saveChanges();
return mm;
}
}

0 0
原创粉丝点击