大家好,我刚刚尝试获取一些Java代码,以通过gmail向Java用户发送电子邮件,这就是我所拥有的:
@ManagedBean
@ViewScoped
public class email {
// Set up the SMTP server.
java.util.Properties props = new java.util.Properties();
public void mail() {
System.out.println("Called mail");
props.put(
"mail.smtp.gmail", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getDefaultInstance(props, null);
// Construct the message
String to = "cam01342@myport.ac.uk";
String from = "richard.dennis@port.ac.uk";
String subject = "Hello";
Message msg = new MimeMessage(session);
try {
System.out.println("Setting up the email");
msg.setFrom(new InternetAddress(from));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
System.out.println("here");
msg.setSubject("Print Job");
msg.setText("Hi,
How are you?");
Transport.send(msg);
System.out.println("Sending message"); //does not get to this part
} catch (MessagingException e) {
// Error.
}
}
}
它在运行等时没有错误,我在控制台中没有收到发送消息,而只是Transport.send(msg)阻塞了我做错了什么? gmail的设置都可以吗?
编辑:
@ManagedBean
@ViewScoped
public class email {
// Set up the SMTP server.
java.util.Properties props = new java.util.Properties();
public void mail() {
System.out.println("Called mail");
String host = "smtp.gmail.com";
String from = "------------";
String pass = "----";
props.put("mail.smtp.starttls.enable", "true"); // added this line
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props,