package cn.guanggong; /** * Created by Administrator on 2017/5/19. */ import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import java.util.Properties; public class JavaMail { /** * user:qq账号 * password:16位口令 * sendTo:接收人 * filePath:需要发送的附件的路径 */ public static String sendMessage(String user,String password,String sendTo,String filePath){ try { final Properties props = new Properties(); // 身份验证 props.put("mail.smtp.auth", "true"); //SMTP服务器 props.put("mail.smtp.host", "smtp.qq.com"); //端口号 props.put("mail.smtp.port", "587"); // 邮箱账号 props.put("mail.user", user); // 密码是16位STMP口令,qq的smtp服务器要在邮箱的设置中开启,之后操作获得口令 props.put("mail.password", password); // 构建授权信息,用于进行SMTP进行身份验证 Authenticator authenticator = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { // 用户名、密码 String userName = props.getProperty("mail.user"); String password = props.getProperty("mail.password"); return new PasswordAuthentication(userName, password); } }; // 创建邮件会话 Session mailSession = Session.getInstance(props, authenticator); // 创建邮件消息 MimeMessage message = new MimeMessage(mailSession); // 设置发件人 InternetAddress from = new InternetAddress( props.getProperty("mail.user")); message.setFrom(from); // 设置收件人的邮箱 InternetAddress to = new InternetAddress(sendTo); message.setRecipient(MimeMessage.RecipientType.TO, to); // 设置邮件标题 message.setSubject("这是来自"+user+"的邮件"); // 创建消息部分 BodyPart messageBodyPart = new MimeBodyPart(); // 消息 messageBodyPart.setText("请接收我发的附件"); // 创建多重消息 Multipart multipart = new MimeMultipart(); // 设置文本消息部分 multipart.addBodyPart(messageBodyPart); // 附件部分 messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filePath); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filePath); multipart.addBodyPart(messageBodyPart); // 发送完整消息 message.setContent(multipart ); // 发送消息 Transport.send(message); System.out.print("Successfully!......."); // 最后当然就是发送邮件啦 Transport.send(message); }catch (Exception e){ e.printStackTrace(); return "ERROR"; } return "SUCCESS"; } }
Java邮件开发简单实例
最新推荐文章于 2024-06-30 08:15:00 发布