使用java向邮箱发送邮件

java 2017-07-28

这是我很早之前写的一个工具类,最近在整理自己所学的东西,无意中找到了,就拿出来与大家分享,代码如下:

import java.io.ByteArrayOutputStream;   
import java.io.FileInputStream;   
import java.io.IOException;   
import java.util.Arrays;   
import java.util.Date;   
import java.util.Properties;   
  



import javax.activation.DataHandler;   
import javax.activation.FileDataSource;   
import javax.mail.Authenticator;   
import javax.mail.Message;   
import javax.mail.PasswordAuthentication;   
import javax.mail.Session;   
import javax.mail.Transport;   
import javax.mail.internet.InternetAddress;   
import javax.mail.internet.MimeMessage;   
  
import javax.mail.BodyPart;   
import javax.mail.Multipart;   
import javax.mail.internet.MimeBodyPart;   
import javax.mail.internet.MimeMultipart;   

import org.apache.struts.util.MessageResources;

import com.qq.connect.javabeans.tenpay.Address;

//import com.sun.istack.internal.ByteArrayDataSource;  
public class SendMails {
       public  int sendMail(String emailTitle, String content, String emailTo,MessageResources message) throws Exception {
        System.out.println(smtpServer1);
        Properties props = new Properties();   
        props.put("mail.smtp.auth", "true"); 
        props.put( "mail.transport.protocol", "smpt");
        props.put("mail.smtp.host", smtpServer1);
        // 获得邮件会话对象   
        Session session = Session.getInstance(props,new SmtpAuthenticator1(fromMailAddress1, password1));  
        /** *************************************************** */  
        // 创建MIME邮件对象   
        MimeMessage mimeMessage = new MimeMessage(session);   
        mimeMessage.setFrom(new InternetAddress(fromMailAddress1));// 发件人   
        mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(emailTo));// 收件人   
        mimeMessage.setSubject(emailTitle);   
        mimeMessage.setSentDate(new Date());// 发送日期   
        Multipart mp = new MimeMultipart("related");// related