java setmessage,Javamail API-如何将setFrom更改为所需的内容?

在尝试通过Gmail发送邮件并更改`setFrom()`方法时遇到问题,显示的发件人地址仍然是用户名。尝试使用Yahoo账号导致认证错误。解决方案是切换到Mandrill服务,使用其SMTP服务器(smtp.mandrillapp.com,端口587),设置用户名为Mandrill账户名,密码为API密钥,成功解决了从地址更改的问题。
摘要由CSDN通过智能技术生成

How do I change the setFrom() method to whatever I want? I can send e-mails through my gmail accoutn and change the setFrom text, but it shows my username for the email. I have tried using my yahoo account as well and I get an authentication error.

I want to change the from address. The code is as follows:

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.InternetAddress;

import javax.mail.internet.MimeMessage;

public class SendMailTLS {

public static void main(String[] args) {

final String username = "username@gmail.com";

final String password = "password";

Properties props = new Properties();

props.put("mail.smtp.auth", "true");

props.put("mail.smtp.starttls.enable", "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("from-email@gmail.com"));

message.setRecipients(Message.RecipientType.TO,

InternetAddress.parse("to-email@gmail.com"));

message.setSubject("Testing Subject");

message.setText("Dear Mail Crawler,"

+ "\n\n No spam to my email, please!");

Transport.send(message);

System.out.println("Done");

} catch (MessagingException e) {

throw new RuntimeException(e);

}

}

}

解决方案

Faced Same problem while using "smtp.gmail.com".

Use Mandrill,it will work.

Once you setup a Mandrill account,use "smtp.mandrillapp.com" on port 587.

For Authentication,set username=your mandrill username and password=API key generated in your account.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值