Java通过gmail发送电子邮件,有时候工作有时挂起

时间:2016-09-22 14:27:03

标签: spring smtp gmail javamail

我通过我的网络应用程序通过Gmail发送电子邮件。

然而,有时它工作正常,但有时它会在没有任何消息的情况下停止。

有谁知道如何解决这个问题?

在我的春天AppConfig.java

Shape

在我的mailService.java

drawAllShapes

有时它的工作正常,我将能够发送邮件,但有时只需停止超过20分钟:

@Bean
    public JavaMailSender getMailSender(){
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost("smtp.gmail.com");
        mailSender.setPort(587);
        mailSender.setUsername("my email from");
        mailSender.setPassword("my email password");

        Properties javaMailProperties = new Properties();
        javaMailProperties.put("mail.smtp.starttls.enable", "true");
        javaMailProperties.put("mail.smtp.auth", "true");
        //javaMailProperties.put("mail.transport.protocol", "smtps");
        javaMailProperties.put("mail.transport.protocol", "smtp");
        javaMailProperties.put("mail.debug", "true");

        mailSender.setJavaMailProperties(javaMailProperties);
        return mailSender;
    }

1 个答案:

答案 0 :(得分:0)

这是我从其他帖子中获得的方法,但我无法回顾这篇文章。 活动是我存储主题和内容的对象之一。

public void sendEmailWithActivity(Activity activity, Object object, String path) {
        try {
            Member member = (Member) object;
            String host = "smtp.gmail.com";
            String username = "email";
            String password = "password";
            String body = activity.getActivity_content();
            String name = activity.getActivity_name();
            String subject = activity.getActivity_subject();=


            //Set the properties
            Properties props = new Properties();
            props.put("mail.smtps.auth", "true");
            // Set the session here
            Session session = Session.getDefaultInstance(props);
            MimeMessage msg = new MimeMessage(session);
            // set the message content here
            msg.setSubject(subject);
            msg.setContent(body, "text/html");
            msg.setFrom(new InternetAddress(username));
            msg.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(member.getEmail()));
            Transport t = session.getTransport("smtps");

            t.connect(host, username, password);
            t.sendMessage(msg, msg.getAllRecipients());
            t.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }

    }