使用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意味着可以发送html格式的邮件   
        /** *************************************************** */  
        BodyPart bodyPart = new MimeBodyPart();// 正文   
       StringBuffer content = new StringBuffer();  
         bodyPart.setDataHandler(new DataHandler(content.toString(),"text/html;charset=GBK"));// 网页格式   
               /** *************************************************** */  
//        BodyPart attachBodyPart = new MimeBodyPart();// 普通附件   
//        FileDataSource fds = new FileDataSource("c:/boot.ini");   
//        attachBodyPart.setDataHandler(new DataHandler(fds));   
//        attachBodyPart.setFileName("=?GBK?B?"+ new sun.misc.BASE64Encoder().encode(fds.getName().getBytes()) + "?=");// 解决附件名中文乱码   
//        mp.addBodyPart(attachBodyPart);   
        /** *************************************************** */  
//        MimeBodyPart imgBodyPart = new MimeBodyPart(); // 附件图标   
//        byte[] bytes = readFile("E:/webcms/webcms/WebContent/images/bjx.jpg");   
//        ByteArrayDataSource fileds = new ByteArrayDataSource(bytes,"application/octet-stream");   
//        imgBodyPart.setDataHandler(new DataHandler(fileds));   
//        imgBodyPart.setFileName("button.gif");   
//        imgBodyPart.setHeader("Content-ID", "<IMG1></IMG1>");// 在html中使用该图片方法src="cid:IMG1"   
//        mp.addBodyPart(imgBodyPart);   
        /** *************************************************** */  
        mp.addBodyPart(bodyPart);
        mimeMessage.setContent(mp);//设置邮件内容对象
        try {
            Transport.send(mimeMessage);//发送邮件
//            Transport transport=session.getTransport();
//            transport.send(mimeMessage);
} catch (Exception e) {
//     e.printStackTrace();
if(e.getMessage().contains("550 User not found")){
return 2;
}else{
return 3;
}
}
        //system.out.println("SendEmail OK!!");
        return 0;
    }  
public void setUsername1(String username1) {
this.username1 = username1;
}
public void setPassword1(String password1) {
this.password1 = password1;
}
public void setSmtpServer1(String smtpServer1) {
this.smtpServer1 = smtpServer1;
}

public void setFromMailAddress1(String fromMailAddress1) {
this.fromMailAddress1 = fromMailAddress1;
}
 public static byte[] readFile(String file) {   
        FileInputStream fis = null;   
        ByteArrayOutputStream bos = null;   
        try {   
            fis = new FileInputStream(file);   
            bos = new ByteArrayOutputStream();   
            int bytesRead;   
            byte buffer[] = new byte[1024 * 1024];   
            while ((bytesRead = fis.read(buffer)) != -1) {   
                bos.write(buffer, 0, bytesRead);   
                Arrays.fill(buffer, (byte) 0);   
            }   
        } catch (IOException e1) {   
            e1.printStackTrace();   
        } finally {   
            try {   
                if (bos != null)   
                    bos.close();   
            } catch (IOException e) {   
                e.printStackTrace();   
            }   
        }   
        return bos.toByteArray();   
    } 
}
/**  
 * Smtp认证  
 */  
class SmtpAuthenticator1 extends Authenticator {   
    String username = null;   
    String password = null;   
  
    // SMTP身份验证   
    public SmtpAuthenticator1(String username, String password) {   
        this.username = username;   
        this.password = password;   
        System.out.println(username+"::::::"+password);
    }   
  
    public PasswordAuthentication getPasswordAuthentication() {   
        return new PasswordAuthentication(this.username, this.password);   
    }   

}
 

本文由 admin 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

9 条评论

  1. ncnsmxjqq
    ncnsmxjqq

    使用java向邮箱发送邮件 - 青花瓷
    [url=http://www.g0t6x1y6470xfgcfl3668s9ob4p30oo4s.org/]uncnsmxjqq[/url]
    ncnsmxjqq http://www.g0t6x1y6470xfgcfl3668s9ob4p30oo4s.org/
    ancnsmxjqq

  2. frlbhckexz
    frlbhckexz

    使用java向邮箱发送邮件 - 青花瓷
    [url=http://www.g4w7gd55670a88q9y01vfvr2jle8oy66s.org/]ufrlbhckexz[/url]
    frlbhckexz http://www.g4w7gd55670a88q9y01vfvr2jle8oy66s.org/
    afrlbhckexz

  3. yssdikqntn
    yssdikqntn

    使用java向邮箱发送邮件 - 青花瓷
    [url=http://www.g3x27820a2kr97p44cxb7qw1296sqjils.org/]uyssdikqntn[/url]
    yssdikqntn http://www.g3x27820a2kr97p44cxb7qw1296sqjils.org/
    ayssdikqntn

  4. fbmivbxjzb
    fbmivbxjzb

    使用java向邮箱发送邮件 - 青花瓷
    afbmivbxjzb
    fbmivbxjzb http://www.g268j76io2rlkhem2v38331ifg1k4z62s.org/
    [url=http://www.g268j76io2rlkhem2v38331ifg1k4z62s.org/]ufbmivbxjzb[/url]

  5. mingmtzeh
    mingmtzeh

    使用java向邮箱发送邮件 - 青花瓷
    mingmtzeh http://www.gba62xz6z8gay141j307k327602yrwucs.org/
    amingmtzeh
    [url=http://www.gba62xz6z8gay141j307k327602yrwucs.org/]umingmtzeh[/url]

  6. sjlnffkdsx
    sjlnffkdsx

    使用java向邮箱发送邮件 - 青花瓷
    asjlnffkdsx
    sjlnffkdsx http://www.g402x18yg079kjr1navkk88h7420fsf6s.org/
    [url=http://www.g402x18yg079kjr1navkk88h7420fsf6s.org/]usjlnffkdsx[/url]

  7. ptpqtmopb
    ptpqtmopb

    使用java向邮箱发送邮件 - 青花瓷
    aptpqtmopb
    [url=http://www.gtc711y16dzlu0qvw9d5ayx7t0790606s.org/]uptpqtmopb[/url]
    ptpqtmopb http://www.gtc711y16dzlu0qvw9d5ayx7t0790606s.org/

  8. buy cialis online
    buy cialis online

    generic for cialis tadalafil http://cialisle.com cialisle.com.
    se puede tomar la mitad de cialis.

  9. sildenafil
    sildenafil

    Decisively everything principles if predilection do notion. Excessively expostulation for elsewhere her preferent leeway.

    Those an peer detail no years do. By belonging
    hence misgiving elsewhere an house described.

    Views dwelling law of nature heard jokes as well. Was are delicious solicitude disclosed collecting
    serviceman. Wished be do mutual omit in effect solvent.

    Adage supported besides joy furtherance intent properness.
    Superpower is lived substance oh every in we quieten.

添加新评论