Email实例
import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.Transport; public class email { public void send(String emailHost, //smtp服务器 String toEmail, //收件人邮箱 String additionalPath, //附件路径 String additionalName, //附件名称 String myEmailUser, //发件邮箱 String myEmailPwd, //密码 String emailTitle, //邮件标题 String context ){ //内容 Properties props = new Properties(); props.put("mail.smtp.emailHost",emailHost); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "587");//qq专用其它不需要 Session session = Session.getDefaultInstance(props); session.setDebug(true); MimeMessage message = new MimeMessage(session); try { message.setFrom(new InternetAddress(myEmailUser)); // 加载发件人地址 message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));// 加载收件人地址 message.setSubject(emailTitle);// 加载标题 Multipart multipart = new MimeMultipart();// 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件 BodyPart contentPart = new MimeBodyPart(); contentPart.setText(context);// 设置邮件的文本内容 multipart.addBodyPart(contentPart); BodyPart messageBodyPart = new MimeBodyPart();// 添加附件 DataSource source = new FileDataSource(additionalPath); messageBodyPart.setDataHandler(new DataHandler(source));// 添加附件的内容 sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder(); messageBodyPart.setFileName("=?GBK?B?"+enc.encode(additionalName.getBytes())+"?="); multipart.addBodyPart(messageBodyPart); message.setContent(multipart);//将multipart对象放到message中 message.saveChanges();// 保存邮件 Transport transport = session.getTransport("smtp");// 发送邮件 transport.connect(emailHost, myEmailUser, myEmailPwd);// 连接服务器的邮箱 transport.sendMessage(message, message.getAllRecipients());// 把邮件发送出去 transport.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { email email = new email(); email.send("smtp.qq.com", "xxxxxxxxx@qq.com", "E:\\text.txt", "附件名称随便", "xxxxxxxxx@qq.com", "xxxxxxxxxrqudbgie",//qq为开启smtp给的密钥,其它为密码 "测试邮件", "我的最新测试邮件!!" ); }