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

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;
}
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值