欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2024-02-12 11:02:10
...

 
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="[email protected]";
            String password="123456";
            String smtp_server="smtp.163.com";
            String from_mail_address=userName;
            String to_mail_address="[email protected]";
            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);
    }

}
相关标签: 开发相关