email发送小案例

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
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;
import javax.mail.internet.MimeMessage.RecipientType;

public class mail {
public static void main(String[] args) throws MessagingException, UnsupportedEncodingException {
//创建邮件服务器//smtp.163.com/smtp.126.com/smtp.yeah.net/smtp.qq.com
Properties props = new Properties();
props.setProperty("mail.host", "smtp.qq.com");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.port", "587");//qq邮件专用,其它一般为25不写
//创建发送邮件对象
Session session = Session.getDefaultInstance(props,new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxxxxxxxxxx@qq.com","xxxxxxxxxxxx");
}//qq需要去邮箱设置开启smtp获取特别密码
});
session.setDebug(true);
MimeMessage mail = new MimeMessage(session);
//设置邮件相应的信息
mail.setFrom(new InternetAddress("xxxxxxxxxxx@qq.com"));
mail.setRecipient(RecipientType.TO, new InternetAddress("yyyyyyyyyyyyyyyy@qq.com"));
mail.setSubject("JAVA测试邮件");
mail.setContent("xxxxxxxxxxxxxxxxxxxxxxxx","text/plain;charset=utf-8");
mail.setSentDate(new Date());
//-------------------------------------------------------------------------------
File file = new File("E:/text.txt");//带附件,多个复制多份或改写成循环语句
MimeBodyPart part = new MimeBodyPart();
DataSource source = new FileDataSource(file);
DataHandler handler = new DataHandler(source);
part.setDataHandler(handler);
part.setFileName(MimeUtility.encodeText(file.getName()) );
MimeMultipart mpart = new MimeMultipart();
mpart.addBodyPart(part);
mail.setContent(mpart);
//-------------------------------------------------------------------------------
Transport.send(mail);//发送邮件
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值