问题描述
如何将setFrom()方法更改为所需的内容?我可以通过gmail accoutn发送电子邮件并更改setFrom文本,但是它显示了电子邮件的username
.我也尝试过使用yahoo帐户,但收到验证错误.
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 = "[email protected]";
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("[email protected]"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("[email protected]"));
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);
}
}
}
推荐答案
遇到的问题使用"smtp.gmail.com"时遇到相同的问题.使用Mandrill,它将起作用.设置Mandrill帐户后,请在端口587上使用"smtp.mandrillapp.com".对于身份验证,请设置用户名=您的山rill用户名和密码=在您的帐户中生成的API密钥.
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.
这篇关于Javamail API-如何将setFrom更改为所需的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!