apach MailUtils邮件发送工具类 支持附件

 

JavaMail Demo,引用的jar如下: 
activation.jar 
mail.jar

smtp设置参考https://www.west.cn/faq/list.asp?Unid=852

示例代码



package com.alexli.uitl;
        import java.util.Date;
        import java.util.Enumeration;
        import java.util.Properties;
        import java.util.Vector;

        import javax.activation.DataHandler;
        import javax.activation.FileDataSource;
        import javax.mail.Authenticator;
        import javax.mail.Message;
        import javax.mail.Multipart;
        import javax.mail.PasswordAuthentication;
        import javax.mail.Session;
        import javax.mail.Transport;
        import javax.mail.internet.InternetAddress;
        import javax.mail.internet.MimeBodyPart;
        import javax.mail.internet.MimeMessage;
        import javax.mail.internet.MimeMultipart;
        import javax.mail.internet.MimeUtility;
/**
 * <p> @Description: 邮件发送工具类 </p>
 * @author alexli
 * @Date   2017年6月22日 上午10:34:41 
 */
public class MailUtils {

    String to = "";         // 收件人邮箱地址
    String from = "";       // 发件人邮箱地址
    String host = "";       // smtp主机
    String username = "";   //用户名
    String password = "";   //密码
    String filename = "";    // 附件文件名
    String subject = "";     // 邮件主题
    String content = "";     // 邮件正文
    Vector file = new Vector();// 附件文件集合

    public MailUtils() {}

    public MailUtils(String to, String from, String smtpServer,
                     String username, String password, String subject, String content) {
        this.to = to;
        this.from = from;
        this.host = smtpServer;
        this.username = username;
        this.password = password;
        this.subject = subject;
        this.content = content;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public void setPassWord(String pwd) {
        this.password = pwd;
    }

    public void setUserName(String usn) {
        this.username = usn;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public void setContent(String content) {
        this.content = content;
    }

    /**
     * @param strText
     * @return
     * @Description: 把主题转为中文 utf-8
     * @author alexli
     * @Date   2017年6月22日 上午10:37:07
     */
    public String transferChinese(String strText) {
        try {
            strText = MimeUtility.encodeText(new String(strText.getBytes(),
                    "utf-8"), "utf-8", "B");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strText;
    }

    public void attachfile(String fname) {
        file.addElement(fname);
    }

    /**
     * @return
     * @Description: 发送邮件,发送成功返回true 失败false
     * @author alexli
     * @Date   2017年6月22日 上午10:37:47
     */
    public boolean sendMail() {

        // 构造mail session
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "25");//465

        Session session = Session.getDefaultInstance(props,
                new Authenticator() {
                    public PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });

        try {
            // 构造MimeMessage 并设定基本的值
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(from));

            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(to));
            subject = transferChinese(subject);
            msg.setSubject(subject);

            // 构造Multipart
            Multipart mp = new MimeMultipart();

            // 向Multipart添加正文
            MimeBodyPart mbpContent = new MimeBodyPart();
            mbpContent.setContent(content, "text/html;charset=utf-8");

            // 向MimeMessage添加(Multipart代表正文)
            mp.addBodyPart(mbpContent);

            // 向Multipart添加附件
            Enumeration efile = file.elements();
            while (efile.hasMoreElements()) {

                MimeBodyPart mbpFile = new MimeBodyPart();
                filename = efile.nextElement().toString();
                FileDataSource fds = new FileDataSource(filename);
                mbpFile.setDataHandler(new DataHandler(fds));
                String filename = new String(fds.getName().getBytes(), "ISO-8859-1");

                mbpFile.setFileName(filename);
                // 向MimeMessage添加(Multipart代表附件)
                mp.addBodyPart(mbpFile);

            }

            file.removeAllElements();
            // 向Multipart添加MimeMessage
            msg.setContent(mp);
            msg.setSentDate(new Date());
            msg.saveChanges();

            // 发送邮件
            Transport transport = session.getTransport("smtp");
            transport.connect(host, username, password);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
        } catch (Exception mex) {
            mex.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * @param args
     * @Description: 邮件测试main方法
     * @author alexli
     * @Date   2017年6月22日 上午10:40:36
     */
    public static void main(String[] args) {
        MailUtils sendmail = new MailUtils();
        sendmail.setHost("smtp.exmail.qq.com");
        sendmail.setUserName("");
        sendmail.setPassWord("");
        sendmail.setTo("");
        sendmail.setFrom("");
        sendmail.setSubject("张小米");
        sendmail.setContent("<a href=\"https://baidu.com\">Link text</a>");
        //添加附件
//      sendmail.attachfile("d:\\CoolFormat3.4.rar");
        System.out.println(sendmail.sendMail());
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 下面是ssmtp.conf文件的配置: # The user that gets all the mails (UID < 1000, usually the admin) root=用户名@126.com# The mail server (where the mail is sent to), both port 465 or 587 should be acceptable mailhub=smtp.126.com:587# The address where the mail appears to come from for user authentication. rewriteDomain=126.com# The full hostname hostname=你的完整域名# Use TLS UseTLS=YES# Use SSL UseSSL=YES# Username/Password AuthUser=用户名@126.com AuthPass=密码# Email 'From header's can override the default domain? FromLineOverride=YES# root 用来指定从哪个用户发送出去的邮件,一般是系统管理员,用户名需要填写完整的邮箱地址 # mailhub 指定邮件服务器的地址,这里使用的是 126.com 邮件服务器,端口是587 # rewriteDomain 指定邮件的发件人地址,这里使用的是 126.com # hostname 指定发送邮件时使用的完整域名 # UseTLS 指定是否使用 TLS 加密 # UseSSL 指定是否使用 SSL 加密 # AuthUser 指定邮件服务器的用户名,即 126.com 邮箱的用户名 # AuthPass 指定邮件服务器的密码,即 126.com 邮箱的密码 # FromLineOverride 指定是否使用默认的域名发件人地址 ### 回答2: 以下是一个在Ubuntu下使用ssmtp和mailutils配合126邮箱配置自动发送邮件的ssmtp.conf配置文件,并对每一行进行解释: 1. root=username@gmail.com 设置邮件发送者的邮箱地址。这里将root用户的邮箱地址设置为username@gmail.com。 2. mailhub=smtp.126.com:25 设置邮件服务器的地址和端口。这里使用126邮箱的SMTP服务器,地址为smtp.126.com,端口为25。 3. hostname=localhost 设置主机名。这里将主机名设置为localhost。 4. AuthUser=username 设置SMTP服务器的登录用户名。这里将用户名设置为username。 5. AuthPass=password 设置SMTP服务器的登录密码。这里将密码设置为password。 6. FromLineOverride=YES 启用覆盖发送者地址。这里设置为YES,表示在邮件头中覆盖发送者的地址。 7. UseSTARTTLS=YES 启用STARTTLS加密协议。这里设置为YES,表示使用STARTTLS协议进行邮件传输的加密。 8. UseTLS=YES 启用TLS加密协议。这里设置为YES,表示使用TLS协议进行邮件传输的加密。 9. TLSCertCheck=NO 禁用TLS证书检查。这里设置为NO,表示不检查邮件服务器的TLS证书。 10. rewriteDomain=gmail.com 重写域名。这里将域名设置为gmail.com,表示通过这个域名发送邮件。 11. hostname=username@gmail.com 设置主机名。这里将主机名设置为username@gmail.com。 12. FromLineOverride=YES 启用覆盖发送者地址。这里设置为YES,表示在邮件头中覆盖发送者的地址。 注意:以上配置仅仅是一个示例,实际使用时需要根据自己的邮箱账号和服务器进行相应的修改。 ### 回答3: ssmtp是一个简单的发送邮件程序,它可以和mailutils库一起使用来在Ubuntu操作系统中自动发送邮件。以下是一个示例的ssmtp.conf配置文件,并对每一行进行解释。 ``` # The file begins with a comment denoted by the '#' symbol. Comments provide explanations or context for the configuration. root=postmaster # This line specifies the email address that will be set as the sender for system-generated emails. In this example, postmaster is used. mailhub=smtp.126.com:587 # This line specifies the SMTP server and the port number to be used for sending emails. smtp.126.com is the domain of the 126 email service, and the port number is set to 587. UseSTARTTLS=YES # This line enables the use of STARTTLS, a protocol extension for establishing a secure connection between the client and the server. Setting it to YES indicates that STARTTLS should be used. AuthUser=your_username@126.com # This line specifies the username for authenticating with the SMTP server. Replace 'your_username' with your actual username for the 126 email service. AuthPass=your_password # This line specifies the password for authenticating with the SMTP server. Replace 'your_password' with your actual password for the 126 email service. FromLineOverride=YES # This line allows the From header in the email to override the default system username. Setting it to YES means the From header will be taken from the email itself, rather than the system username. ``` 当你按照上述配置文件设置ssmtp.conf后,可以使用ssmtp命令结合mailutils库在Ubuntu下自动发送邮件,而该邮件将通过126邮件服务器发送出去。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值