赞
踩
创建project我们就不介绍了,直接上代码:
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; 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; public class EmailTest { public static void main(String[] args) { String to = "收件人邮箱"; String from = "发件人邮箱"; String host = "SMTP服务器地址"; String username = "发件人邮箱用户名"; String password = "发件人邮箱密码"; String filePath = "附件文件路径"; Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); properties.setProperty("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() { protected javax.mail.PasswordAuthentication getPasswordAuthentication() { return new javax.mail.PasswordAuthentication(username, password); } }); try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("带附件的邮件"); MimeBodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setText("这是一封带附件的邮件"); MimeBodyPart attachmentBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filePath); attachmentBodyPart.setDataHandler(new DataHandler(source)); attachmentBodyPart.setFileName("附件文件名"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(textBodyPart); multipart.addBodyPart(attachmentBodyPart); message.setContent(multipart); Transport.send(message); System.out.println("邮件已发送"); } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。