此代码工作正常,但我只能通过静态邮件jhon.doe@gmail.com
发送邮件。是否有启用Gmail登录的解决方案,以便我可以获取用户名和密码来发送邮件?
这是我的代码:
public class EmailSender {
private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
public static boolean SendEmail(String to, String subject, String msg)
{
final String username = "jhon.doe@gmail.com";
final String password = "abcd12345";
boolean flag = false;
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.socketFactory.port", "587");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
props.put("mail.smtp.socketFactory.fallback", "false");
Session session = Session.getInstance(props, new javax.mail.Authenticator()
{
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("jhon.doe@gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(subject);
message.setContent(msg, "text/html; charset=utf-8");
Transport.send(message);
flag = true;
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
return flag;
}
}
JSF代码页:
<h:outputText value="Message" />
<br></br>
<p:inputTextarea rows="10" cols="50" completeMethod="#{inputTextareaView.completeArea}" value="#{faqbean.message}" queryDelay="750" minQueryLength="4" />
<br></br>
<p:commandButton action="#{faqbean.send()}" value="Send To Support" ajax="true"/>