java实现邮件发送,解决附件中文乱码问题

 
import java.io.FileInputStream;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
public class MySendEmail {
    public static void main(String[] args) {
        try{
            String userName="FromMail@163.com";
            String password="123456";
            String smtp_server="smtp.163.com";
            String from_mail_address=userName;
            String to_mail_address="ToMail@126.com";
            Authenticator auth=new PopupAuthenticator(userName,password);
            Properties mailProps=new Properties();
            mailProps.put("mail.smtp.host", smtp_server);
            mailProps.put("mail.smtp.auth", "true");
            mailProps.put("username", userName);
            mailProps.put("password", password);
            Session mailSession=Session.getDefaultInstance(mailProps, auth);
            mailSession.setDebug(true);
            MimeMessage message=new MimeMessage(mailSession);
            message.setFrom(new InternetAddress(from_mail_address));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(to_mail_address));
            message.setSubject("Mail Test");
            // message.setSentDate(new Date()); // 设置邮件发送日期
            MimeMultipart multi=new MimeMultipart();
            String fileName = "E:\\文件验证.docx"; //发送附件的文件路径
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            //邮件内容
            messageBodyPart.setText("Hi there is message info ");   
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(fileName);
            messageBodyPart.setDataHandler(new DataHandler(source));
            // 处理附件名称中文(附带文件路径)乱码问题
            messageBodyPart.setFileName(MimeUtility.encodeText(fileName));
            multipart.addBodyPart(messageBodyPart);
            message.setContent(multipart);
            Transport.send(message);
        }catch(Exception ex){
            System.err.println("邮件发送失败的原因是:"+ex.getMessage());
            System.err.println("具体的错误原因");
            ex.printStackTrace(System.err);
        }
    }
}

//邮件账户验证

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class PopupAuthenticator extends Authenticator {
    private String username;
    private String password;
    public PopupAuthenticator(String username,String pwd){
        this.username=username;
        this.password=pwd;
    }
    public PasswordAuthentication getPasswordAuthentication(){
        return new PasswordAuthentication(this.username,this.password);
    }

}
发送带有base64格式图片的HTML邮件,可以按照以下步骤进行: 1. 将base64格式的图片解码为字节数组。 2. 使用JavaMail API创建MimeMultipart对象。 3. 创建MimeBodyPart对象,并设置内容为HTML文本,同时将图片以附件形式添加到MimeBodyPart对象中。 4. 将MimeBodyPart对象添加到MimeMultipart对象中。 5. 使用JavaMail API发送邮件。 下面是一个示例代码,用于发送带有base64格式图片的HTML邮件: ```java import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.*; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class MailSender { public static void main(String[] args) throws Exception { String host = "smtp.gmail.com"; String port = "587"; String username = "你的邮箱地址"; String password = "你的邮箱密码"; Properties props = new Properties(); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.ssl.trust", host); Session session = Session.getDefaultInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); String toEmail = "收件人邮箱地址"; String subject = "测试邮件"; String htmlContent = "<html><body><h1>这是一张图片</h1><br><img src='cid:image'/></body></html>"; String imageBase64 = "base64编码的图片"; MimeMultipart multipart = new MimeMultipart("related"); MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(htmlContent, "text/html;charset=UTF-8"); multipart.addBodyPart(htmlPart); byte[] imageData = decodeBase64(imageBase64); DataSource ds = new ByteArrayDataSource(imageData, "image/jpeg"); MimeBodyPart imagePart = new MimeBodyPart(); imagePart.setDataHandler(new DataHandler(ds)); imagePart.setHeader("Content-ID", "<image>"); multipart.addBodyPart(imagePart); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(username)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail)); message.setSubject(subject); message.setContent(multipart); Transport.send(message); } private static byte[] decodeBase64(String base64) { try { InputStream stream = new ByteArrayInputStream(base64.getBytes()); return javax.mail.util.Base64.decodeBase64(stream); } catch (IOException e) { throw new RuntimeException(e); } } private static class ByteArrayDataSource implements DataSource { private final byte[] data; private final String type; public ByteArrayDataSource(byte[] data, String type) { this.data = data; this.type = type; } public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(data); } public OutputStream getOutputStream() throws IOException { throw new IOException("Not supported"); } public String getContentType() { return type; } public String getName() { return "ByteArrayDataSource"; } } } ``` 在上面的代码中,我们使用了JavaMail API发送邮件,并使用了MimeMultipart、MimeBodyPart等类来创建HTML邮件,并将base64格式的图片嵌入到HTML中。同时,我们还使用了javax.mail.util.Base64类对图片进行解码,并使用了ByteArrayDataSource类将字节数组包装成DataSource对象,以便将图片作为附件添加到邮件中。 如果HTML邮件中的中文出现乱码,可以尝试将邮件内容的编码方式设置为UTF-8,如下所示: ```java htmlPart.setContent(htmlContent, "text/html;charset=UTF-8"); ``` 同时,可以将邮箱客户端的编码方式设置为UTF-8,以便正确显示邮件内容。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值