Java 使用Gmail Smtp发送邮件时出现异常?
我正在尝试使用Gmail smtp服务器发送邮件Java 使用Gmail Smtp发送邮件时出现异常?,java,email,gmail,Java,Email,Gmail,我正在尝试使用Gmail smtp服务器发送邮件 package com; import java.util.Properties; import javax.mail.Message; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax
package com;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Email {
public static void main(String[] args) {
try
{
String host = "smtp.gmail.com";
final String from = "myuname@gmail.com";
final String pass = "mypassword";
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", "true");
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");
String[] to = {"to@gmail.com"};
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, pass);
}
});
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i=0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
System.out.println(Message.RecipientType.TO);
for( int i=0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject("sending in a group");
message.setText("Welcome to JavaMail");
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}catch (Exception e) {
System.out.println(e);
}
}
}
如何删除此错误?
提前感谢。一个更简单的选择是使用apache commons邮件
import org.apache.commons.mail.*;
Email email = new SimpleEmail();
email.setHostName("smtp.googlemail.com");
email.setSmtpPort(465);
email.setAuthenticator(new DefaultAuthenticator("username", "password"));
email.setSSL(true);
try{
email.setFrom("yourID@gmail.com");
email.setSubject("hello");
String s="hi"
email.setMsg(s);
email.addTo(id);
email.send();
我想问题出在我的电子邮件Id上。 我创建了一个新的,它正在工作
谢谢大家。这可能是重复的吗?你真的能连接到smtp.gmail.com 587吗?试试telnet smtp.gmail.com 587?防火墙规则可能会阻止连接。@beny23我可以在哪里运行此命令telnet??您是否有实际的smtp客户端连接到此服务器?我不知道。我正在从
import org.apache.commons.mail.*;
Email email = new SimpleEmail();
email.setHostName("smtp.googlemail.com");
email.setSmtpPort(465);
email.setAuthenticator(new DefaultAuthenticator("username", "password"));
email.setSSL(true);
try{
email.setFrom("yourID@gmail.com");
email.setSubject("hello");
String s="hi"
email.setMsg(s);
email.addTo(id);
email.send();