Java发送邮件带附件
import com.sun.xml.internal.bind.v2.util.DataSourceSource; 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 hello { public static void main(String[] args) { String from = "cm1@leejay.vip"; //发件人电子邮箱 String passwd = "PAamuden33cPIBpC"; String to = "cm2@leejay.vip"; //收件人电子邮箱 String server = "192.168.173.14"; //发件邮件的主机服务器 Properties properties = System.getProperties(); //获取系统属性 // System.out.println(properties); //设置邮件服务器 properties.setProperty("mail.smtp.host", server); properties.put("mail.smtp.auth", "true"); //获取默认session对象 Session session = Session.getDefaultInstance(properties, new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, passwd); } }); try{ MimeMessage message = new MimeMessage(session); //创建默认的MimeMessage对象 message.setFrom(new InternetAddress(from)); //设置头部的from message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));//设置头部的收件人 message.setSubject("This is the java test mail"); //主题 //创建消息部分 BodyPart messageBodyPart = new MimeBodyPart(); //消息 messageBodyPart.setText("This is a message body."); //创建多重消息 Multipart multipart = new MimeMultipart(); //设置文本消息 multipart.addBodyPart(messageBodyPart); //附件部分 messageBodyPart = new MimeBodyPart(); String filename = "C:\\Users\\coremail\\Desktop\\白皮书\\[www.java1234.com]鸟哥的Linux私房菜-基础篇.第四版.pdf"; DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); //发送完整消息 message.setContent(multipart); //发送邮件 Transport.send(message); System.out.println("Sent message successfully..."); }catch (Exception e){ System.out.println(e); } } }