我有一个简单的javamail类来通过SMTP发送电子邮件。只要我只从一个地址发送电子邮件,它就可以工作。如果我尝试使用其他地址,它会出于某种原因引发此异常:
com.sun.mail.smtp.SMTPSendFailedException: 550 5.1.0 Use your own address, please.
这是我的班级:
public class EmailSender { private static final String HOST = "xxxx.xxxxxx.xx"; private static final String PORT = "xx"; public static boolean sendMail(String from, String to, String pass, String subject, String text){ Properties properties = new Properties(); properties.setProperty("mail.smtp.host", HOST); properties.setProperty("mail.smtp.port", PORT); properties.setProperty("mail.smtp.auth", "true"); properties.setProperty("mail.user", from); properties.setProperty("mail.password", pass); Session session = Session.getDefaultInstance(properties, new CustomAuthenticator(from, pass)); try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setText(text); Transport.send(message); return true; }catch (MessagingException e) { e.printStackTrace(); return false; } } }
如果您想知道,CustomAuthenticator类看起来像这样:
public class CustomAuthenticator extends Authenticator{ private String user; private String pw; public CustomAuthenticator (String username, String password){ super(); this.user = username; this.pw = password; } public PasswordAuthentication getPasswordAuthentication(){ return new PasswordAuthentication(user, pw); } }
答案 0 :(得分:0)
您的服务器不会让您使用不属于您的地址。根据您的服务器,可能有一种方法可以说服其他地址也是您的。通常"你的"表示"与您登录时使用的帐户关联的地址"。
答案 1 :(得分:0)
所以我发现解决方案是使用SMTPTransport类。
public class EmailSender { private static final String HOST = "xxxx.xxxxxx.xx"; private static final String PORT = "xx"; public static boolean sendMail(String from, String to, String pass, String subject, String text){ Properties properties = new Properties(); properties.setProperty("mail.smtp.port", PORT); properties.setProperty("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(properties, new CustomAuthenticator(from, pass)); try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setText(text); SMTPTransport tp = (SMTPTransport)session.getTransport(); tp.connect(HOST, from, pass); tp.sendMessage(message, message.getAllRecipients()); tp.close(); return true; }catch (MessagingException e) { e.printStackTrace(); return false; } } }