JAVA发送邮件代码

该博客展示了如何在Java中使用JavaMail API发送带有HTML内容和多个图片附件的邮件。通过设置SMTP服务器参数、创建MimeMessage、MimeBodyPart以及MimeMultipart,实现了包括正文、收件人、抄送人、主题和图片附件在内的完整邮件发送功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.bugfree.mail;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
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.MessagingException;
import javax.mail.PasswordAuthentication;  
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;  
import com.bugfree.bugcount.GetNumber;
import com.bugfree.servlet.BugAppointServlet;
import com.bugfree.servlet.BugCreateServlet;
import com.bugfree.servlet.BugModuleServlet;
import com.bugfree.servlet.BugSolveServlet;
   
public class SendMail {  
    // JavaMail需要Properties来创建一个session对象。它将寻找字符串"mail.smtp.host",属性值就是发送邮件的主机.  
    //public static void main(String[] args) throws AddressException, MessagingException, UnsupportedEncodingException, IOException {
	public void sendMail(String[]toMore, String[] ccMore) throws Exception{
    	
           // 设定连接的相关参数
           HttpURLConnection connection= (HttpURLConnection) url.openConnection();
           connection.setDoOutput(true);
           connection.setRequestMethod("POST");
           OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
           // 向服务端发送key = value对
           out.write("project="+projectName+"&module="+moduleName);
           out.flush();
           out.close();
    	
        Properties properties = new Properties();  
        // properties.put("mail.smtp.host", "mailcas.chinapnr.com");// 设置smtp主机  
        properties.put("mail.smtp.host", "10.10.0.210");// 设置smtp主机  
        properties.put("mail.smtp.auth", "false");// 使用smtp身份验证  
        /* 
         * 在 JavaMail 中,可以通过 extends Authenticator 抽象类,在子类中覆盖父类中的 
         * getPasswordAuthentication() 方法,就可以实现以不同的方式来进行登录邮箱时的用户身份认证。JavaMail 
         * 中的这种设计是使用了策略模式(Strategy 
         */  
        MimeMessage message = new MimeMessage(Session.getInstance(properties,  
                new Authenticator() {  
                    public PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(//设置发送帐号密码  
                                "software", "Soft.Ware");  
                    }  
                }));  
        // 设置邮件的属性
        // 设置邮件的发件人
        message.setFrom(new InternetAddress("software@pantum.local"));  
        // 设置邮件的收件人 cc表示抄送 bcc 表示暗送  
        message.setRecipient(Message.RecipientType.BCC, new InternetAddress("yipei.zhao@pantum.local"));  
        // 设置邮件的主题  
        message.setSubject("xxxxxxxxx邮件主题xxxxxxxx");  
        // 创建邮件的正文  
        MimeBodyPart text = new MimeBodyPart();  
        //setContent(“邮件的正文内容”,”设置邮件内容的编码方式”)  
        text.setContent("*******HTML代码*********");
        
        // 点到点的发送  
        // 一对多发送只要改一个地方如下:  
           
        // 构建一个群发地址数组  
        //ArrayList toMore = new ArrayList();
        //String[] toMore = {"software@pantum.local"};
        InternetAddress[] adr=new InternetAddress[toMore.length];  
            for(int i=0;i<toMore.length;i++){ 
        	adr[i]=new  InternetAddress(toMore[i]); 
        	}  
         //Message的setRecipients方法支持群发。。注意:setRecipients方法是复数和点 到点不一样  
         message.setRecipients(Message.RecipientType.TO,adr);  
         
         //群抄送
         InternetAddress[] cc=new InternetAddress[ccMore.length];  
         for(int i=0;i<ccMore.length;i++){ 
        	 cc[i]=new  InternetAddress(ccMore[i]); 
     	}  
        message.setRecipients(Message.RecipientType.CC,cc);  
            
 
        /* 
         * JavaMail API不限制信息只为文本,任何形式的信息都可能作为MimeMessage的一部分. 
         * 除了文本信息,作为文件附件包含在电子邮件信息的一部分是很普遍的. JavaMail 
         * API通过使用DataHandler对象,提供一个允许我们包含非文本BodyPart对象的简便方法. 
         */ 
        
        // 创建图片  
        MimeBodyPart img = new MimeBodyPart(); 
        DataHandler dh = new DataHandler(new FileDataSource("C://bugReport//WebRoot//images2//solve"+cTime+".jpg"));//图片路径  
        img.setDataHandler(dh);  
        // 创建图片的一个表示用于显示在邮件中显示  
        img.setContentID("a");  
   
        MimeBodyPart img2 = new MimeBodyPart();  
        DataHandler dh2 = new DataHandler(new FileDataSource("C://bugReport//WebRoot//images2//create"+cTime+".jpg"));//第二张图片路径  
        img2.setDataHandler(dh2);  
        img2.setContentID("b");  
        
        MimeBodyPart img3 = new MimeBodyPart();  
        DataHandler dh3 = new DataHandler(new FileDataSource("C://bugReport//WebRoot//images2//module"+cTime+".jpg"));//第三张图片路径  
        img3.setDataHandler(dh3);  
        img3.setContentID("c");  
        
        MimeBodyPart img4 = new MimeBodyPart();  
        DataHandler dh4 = new DataHandler(new FileDataSource("C://bugReport//WebRoot//images2//appoint"+cTime+".jpg"));//第四张图片路径  
        img4.setDataHandler(dh4);  
        img4.setContentID("d");  
        // 创建附件  
        // MimeBodyPart attch = new MimeBodyPart();  
        // DataHandler dh1 = new DataHandler(new FileDataSource("src//b.jpg"));  
        // attch.setDataHandler(dh1);  
        // String filename1 = dh1.getName();  
        // MimeUtility 是一个工具类,encodeText()用于处理附件字,防止中文乱码问题  
        // attch.setFileName(MimeUtility.encodeText(filename1));  
        // 关系 正文和图片的
        
        MimeMultipart mm = new MimeMultipart();  
        mm.addBodyPart(text);
        mm.addBodyPart(img);
        mm.addBodyPart(img2);
        mm.addBodyPart(img3);
        mm.addBodyPart(img4);
        mm.setSubType("mixed");
        message.setContent(mm);
        message.saveChanges(); // 保存修改  
        Transport.send(message);// 发送邮件  
        System.out.println("邮件发送成功");  
    }  
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值