关于JAVA邮件发送功能的代码 5C

我在一个main函数中可以测试到邮件发送了 并且邮箱有反应
但是单独的拿到工具类中就会出错 我想问怎么将发送邮件的代码
封装成工具类??????

16个回答

 package util;

import bean.EmailSenderInfo;
import bean.ScheduleEmailBean;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.Multipart;
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.util.ByteArrayDataSource;

import listener.ResourceConfiger;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class MailSendUtil
{
  private static final Log logger = LogFactory.getLog(MailSendUtil.class);

  public void sendMail(byte[] content, ScheduleEmailBean salesFollowupBean) throws IOException
  {
    logger.debug("==== MailSendUtil.sendMail() start====");

    EmailSenderInfo mailSenderInfo = new EmailSenderInfo();
    try
    {
      mailSenderInfo.setMailServerHost(
        ResourceConfiger.get("email.server.host"));
      mailSenderInfo.setTransport(
        ResourceConfiger.get("email.server.transport"));
      mailSenderInfo.setFromAddress(
        ResourceConfiger.get("email.from.address"));
      mailSenderInfo.setUserName(
        ResourceConfiger.get("email.from.userName"));
      mailSenderInfo.setPassword(
        ResourceConfiger.get("email.from.userPassword"));
      String[] toadderss = salesFollowupBean.getRecipients();

      mailSenderInfo.setSubject(salesFollowupBean.getSubject());

      mailSenderInfo.setToAddress(toadderss[0]);
      mailSenderInfo.setToAddressArray(toadderss);

      mailSenderInfo.setDoSend(true);
      mailSendProccess(mailSenderInfo, content);
    } catch (IOException ex) {
      ex.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void mailSendProccess(EmailSenderInfo mailSenderInfo, byte[] content)
    throws Exception
  {
    Properties props = new Properties();
    props.put("mail.smtp.host", mailSenderInfo.getMailServerHost());
    props.put("mail.smtp.auth", "true");

    Session session = Session.getInstance(props);
    session.setDebug(true);

    MimeMessage message = new MimeMessage(session);
    message.setSubject(mailSenderInfo.getSubject(), "utf-8");
    message.setSentDate(new Date());
    message.setFrom(new InternetAddress(mailSenderInfo.getFromAddress()));

    String[] mailToArray = mailSenderInfo.getToAddressArray();
    if ((mailToArray == null) || (mailToArray.length == 0)) {
      InternetAddress toAddress = new InternetAddress(
        mailSenderInfo.getToAddress());
      message.setRecipient(Message.RecipientType.TO, toAddress);
    } else {
      InternetAddress[] toAddressList = new InternetAddress[mailToArray.length];
      for (int index = 0; index < mailToArray.length; ++index) {
        if ((toAddressList == null) || (mailToArray[index] == null) || 
          (mailToArray[index].trim().length() <= 0)) continue;
        toAddressList[index] = 
          new InternetAddress(mailToArray[index]);
      }

      message.addRecipients(Message.RecipientType.TO, toAddressList);
    }

    Multipart multipart = new MimeMultipart();
    MimeBodyPart iCalAttachment = new MimeBodyPart();

    iCalAttachment.setDataHandler(
      new DataHandler(new ByteArrayDataSource(new ByteArrayInputStream(content), 
      "text/calendar;method=REQUEST;charset=\"UTF-8\"")));
    multipart.addBodyPart(iCalAttachment);
    message.setContent(multipart);
    Transport tranSport = session.getTransport(mailSenderInfo
      .getTransport());
    tranSport.connect(mailSenderInfo.getMailServerHost(), 
      mailSenderInfo.getUserName(), mailSenderInfo.getPassword());
    tranSport.sendMessage(message, message.getAllRecipients());
    tranSport.close();
    logger.info("........send mail success....");
  }
}

@ResponseBody
@RequestMapping("/getpassfound")
public String Getpassfound(HttpServletRequest request) throws Exception{
System.out.println("到这了1");
String scode=request.getParameter("xuehao");
//根据scode给邮箱发送信息
System.out.println("到这了2"+scode);
int sid=userService.getIdByscode(scode);
//System.out.println(sid);
String email=userService.getEmailById(sid);
String name=userService.getNameBycode(scode);
String sex=userService.getSexById(sid);

        System.out.println("email:"+email+","+"name:"+name);
        /**
         * 将email name  sex  发送过去  进行确认
         */
         Properties props = new Properties();
         // 开启debug调试
         props.setProperty("mail.debug", "true");
         // 发送服务器需要身份验证
         props.setProperty("mail.smtp.auth", "true");
         // 设置邮件服务器主机名
         props.setProperty("mail.host", "smtp.qq.com");
         // 发送邮件协议名称
         props.setProperty("mail.transport.protocol", "smtp");
         MailSSLSocketFactory sf = new MailSSLSocketFactory();
         sf.setTrustAllHosts(true);
         props.put("mail.smtp.ssl.enable", "true");
         props.put("mail.smtp.ssl.socketFactory", sf);
         Session session = Session.getInstance(props);
         String chenwei=null;
         if(sex=="男"){
            chenwei="先生";
         }
         else {
            chenwei="女士";
        }

         Message msg = new MimeMessage(session);
         msg.setSubject("密码重置信息");
         StringBuilder builder = new StringBuilder();
        builder.append(name+chenwei+":<br>请登陆以下链接重置密码:"+"http://www.baidu.com");
         msg.setText(builder.toString());
         msg.setFrom(new InternetAddress("2365956483@qq.com"));
         msg.setSentDate(new Date());
         Transport transport = session.getTransport();
         //upehnpvwyzgvdidc

transport.connect("smtp.qq.com", "qq邮箱", "ssl密码");//显示的是这里出错530 ssl我也验证过 手机也获得了密码 仙剑java工程可以运行发送 但是在项目里 就不行了

         transport.sendMessage(msg, new Address[] { new InternetAddress(email) });
         transport.close();
        return "ok";
    }

1、把pop3和smtp服务都开通;2、指定服务器端口587试试 props.setProperty("mail.port", 587);3、看看堆栈信息有没有其他报错,是否是由于其他报错导致不能验证登录

DreameGirl
DreameGirl 123
一年多之前 回复
DreameGirl
DreameGirl buxing
一年多之前 回复
qq_34654085
张小北2 能加个好友吗
一年多之前 回复
qq_34654085
张小北2 不行啊....错误代码如下
一年多之前 回复

EHLO PC
250-smtp.qq.com
250-PIPELINING
250-SIZE 73400320
250-STARTTLS
250-AUTH LOGIN PLAIN
250-AUTH=LOGIN
250-MAILCOMPRESS
250 8BITMIME
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "SIZE", arg "73400320"
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN"
DEBUG SMTP: Found extension "AUTH=LOGIN", arg ""
DEBUG SMTP: Found extension "MAILCOMPRESS", arg ""
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Attempt to authenticate
AUTH LOGIN
334 VXNlcm5hbWU6
MjM2NTk1NjQ4M0BxcS5jb20=
530 Error: A secure connection is requiered(such as ssl). More information at http://service.mail.qq.com/cgi-bin/help?id=28
错误如下:

三月 24, 2018 1:03:08 下午 org.apache.catalina.core.StandardWrapperValve invoke
严重: Servlet.service() for servlet [mvc-dispatcher] in context with path [/ssm2] threw exception [Request processing failed; nested exception is javax.mail.AuthenticationFailedException] with root cause
javax.mail.AuthenticationFailedException
at javax.mail.Service.connect(Service.java:306)
at javax.mail.Service.connect(Service.java:156)
at com.cn.controller.UserController.Getpassfound(UserController.java:485)

图片说明

打马赛克的地方就是报错的地方

你把main方法代码给我,我给你封装成工具类

qq_34654085
张小北2 代码就是 我上面的那段:
一年多之前 回复
 package com.test.demo;

import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.sun.mail.util.MailSSLSocketFactory;

public class EmailSender {
    private static final String FROM_EMAIL = "发送邮箱";
    private static final String SSL_PASSWORD = "发送邮箱密码";
    private static Properties props;
    static {
        props = new Properties();
        // 指定协议
        props.put("mail.transport.protocol", "smtp");
        // 主机 smtp.qq.com
        props.put("mail.smtp.host", "smtp.qq.com");
        // 用户密码认证
        props.put("mail.smtp.auth", "true");
        // 调试模式
        props.put("mail.debug", "true");
        props.setProperty("mail.transport.protocol", "smtp");
        try {
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            props.put("mail.smtp.ssl.enable", "true");
            props.put("mail.smtp.ssl.socketFactory", sf);
        } catch (GeneralSecurityException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public static void send(String recipients, String subject, String content)
            throws Exception {
        Session session = Session.getInstance(props);
        // 创建邮件对象
        // 设置邮件收件人
        Message msg = new MimeMessage(session);
        msg.setSubject(subject);
        msg.setText(content);
        msg.setFrom(new InternetAddress(FROM_EMAIL));
        String[] recipientArray = recipients.split(",");
        Address[] addrs = new Address[recipientArray.length];
        for (int i = 0; i < recipientArray.length; i++) {
            addrs[i] = new InternetAddress(recipientArray[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addrs);
        msg.setSentDate(new Date());
        Transport transport = null;
        try {
            transport = session.getTransport();
            transport.connect(FROM_EMAIL, SSL_PASSWORD);
            transport.sendMessage(msg, msg.getAllRecipients());
        } finally {
            if (transport != null) {
                transport.close();
            }
        }
    }
}

这是我写的一个工具类,本地测试是可以运行的。如果你放到项目上发现不能运行。看看是不是项目的javamail版本有问题

qq_34654085
张小北2 我用了你的代码 但是 还是包530 图片如下
一年多之前 回复

MailSSLSocketFactory应该是javamail1.4以后的版本才可以

qq_34654085
张小北2 我把我的代码放到下面了 你帮我看看 为什么这段代码 放到main函数里单独运行可以 放到项目中封装成工具类 就报530
一年多之前 回复

Properties props = new Properties();
// 开启debug调试
props.setProperty("mail.debug", "true");
// 发送服务器需要身份验证
props.setProperty("mail.smtp.auth", "true");
// 设置邮件服务器主机名
props.setProperty("mail.host", "smtp.qq.com");

    // 发送邮件协议名称
    props.setProperty("mail.transport.protocol", "smtp");
    MailSSLSocketFactory sf = new MailSSLSocketFactory();
    sf.setTrustAllHosts(true);
    props.put("mail.smtp.ssl.enable", "true");
    props.put("mail.smtp.ssl.socketFactory", sf);

    Session session = Session.getInstance(props);

    Message msg = new MimeMessage(session);
    msg.setSubject("密码重置信息");
    msg.setSentDate(new Date());
    msg.setDescription("只是一封来自Dou都教务的邮件");
    StringBuilder builder = new StringBuilder();
    builder.append(":<br>请点击确定以重置密码:<a href=''>确定</a>");
    msg.setText(builder.toString());
    msg.setFrom(new InternetAddress("邮箱地址"));
    Transport transport = session.getTransport();
    transport.connect("smtp.qq.com", "qq邮箱", "password");
    transport.sendMessage(msg, new Address[] { new InternetAddress("2365778965@qq.com") });
    transport.close();
共16条数据 1 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!