我尝试通过Java应用程序发送电子邮件。但无法连接到Gmail主机。 有人可以给我支持吗?它已经可以在家里与我的Eclipse Oxygen一起使用,但是在我在工作中使用的环境中,它总是会失败。非常感谢您的帮助:)
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
public static void main(String[] args) {
final String username = "myemail@gmail.com";
final String password = "mypassword";
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("myemail@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("mysendtoemail@outlook.com"));
message.setSubject("Testbetreff");
message.setText("Sehr geehrter Herr gng76u76ihn,"
+ "\n\n Testnachricht");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}