java gmail 发送邮件_Java通过Gmail发送电子邮件

本文档详细记录了一位开发者在使用Java通过Gmail发送邮件时遇到的问题,包括SMTP连接被阻塞及`javax.mail.MessagingException`异常。通过添加`mail.smtp.starttls.enable`属性和调整端口为587来解决连接问题,但最终遇到了`Connection timed out`错误,可能的原因是网络连接问题或Gmail SMTP服务器的配置问题。
摘要由CSDN通过智能技术生成

大家好,我刚刚尝试获取一些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,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值