I am trying to send an email to a yahoo email account with this code.
However, I get this message:
javax.mail.MessagingException: Could not connect to SMTP host: winmo.smtp.mail.yahoo.com, port: 465, response: -1
I dont know what is wrong. I am new to java.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String to = "myemail#yahoo.com";
System.out.println("Type the subject of the email");
String subject = s.nextLine();
System.out.println("Type the content of the message");
String body = s.nextLine();
String from = "web#gmail.com";
String host = "winmo.smtp.mail.yahoo.com";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.port", "465");
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
message.setText(body);
Transport.send(message);
System.out.println("sent");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
Related
When I tried to send mail using following code, I got authentication issues.
Here's my code:
public class NewSendMail {
String to = "********";
String subject = "subject";
String msg ="email text....";
final String from ="*******";
final String password ="******";
public NewSendMail(){
}
public boolean sendMymail(){
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.debug", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from,password);
}
});
// Session session = Session.getDefaultInstance(props);
//session.setDebug(true);
Transport transport;
InternetAddress addressFrom = null;
try {
transport = session.getTransport();
addressFrom = new InternetAddress(from);
MimeMessage message = new MimeMessage(session);
message.setSender(addressFrom);
message.setSubject(subject);
message.setContent(msg, "text/plain");
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
transport.connect();
Transport.send(message);
transport.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
}
It is throwing a javax.mail.AuthenticationFailedException.
How can I fix the issue?
The following code may help you
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Email {
private static String USER_NAME = "username"; // GMail user name (just the part before "#gmail.com")
private static String PASSWORD = "password"; // GMail password
private static String RECIPIENT = "xxxxx#gmail.com";
public static void main(String[] args) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "hi ....,!";
sendFromGMail(from, pass, to, subject, body);
}
private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.ssl.trust", 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);
MimeMessage message = new MimeMessage(session);
try {
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]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}
This code worked for me, If it is not working for you, Check your jar files
I tell everyone who asks for JavaMail help the same things. (I wonder why they call it a FAQ?)
Fix these common mistakes.
Follow this example for Gmail.
Turn on session debugging to get more details of what's going wrong, and post the output if you still can't figure it out.
Either you're sending the wrong username or password, or the server is rejecting your login attempt for other reasons, perhaps because you haven't enabled less secure apps.
I'm trying to send mass emails, Achievement send 20 emails on average and then I get this error:
javax.mail.MessagingException: Can't send command to SMTP host; nested exception is: java.net.SocketException: Connection closed by remote host
CODE JAVA:
public void mandarEmail(String correos, String mensaje, String asunto) {
final String username = "docs-gf#usmp.pe";
final String password = "Docpass";
Message message;
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.port", "587");
props.put("mail.smtp.host", "pod51004.outlook.com");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
message = new MimeMessage(session);
message.setFrom(new InternetAddress("Hello my friend"));
message.setSubject("I love u very much");
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("ivan#hotmail.com"));
message.setContent(mensaje, "text/html; charset=utf-8");
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
} finally {
props = null;
message = null;
}
}
I'm forgetting something?
Probably the server doesn't want you to send mass emails and so is rate limiting you. Turn on JavaMail Session debugging and there might be more information from the server in the protocol trace.
While sending the email after the script completed i am not able to add any body part. I want to add body like,
Hi xyz,
Please find the attached the reports attached.
With Best Regards,
Abc.
I am using the below code for sending the email . Can anyone please guide me how to send email.
package util;
//set CLASSPATH=%CLASSPATH%;activation.jar;mail.jar
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class SendMail
{
public static void zipAndSendReport()
{
TestUtil.zip(System.getProperty("user.dir") +"\\HtmlReports");
String[] to={"xyz#xyz.com"};
String[] cc={"xyzff#xyz.com","xyzaa#xyz.com"};
String[] bcc={"xyzrwer#xyz.com"};
//This is for google
SendMail.sendMail("acv.ddg#gmail.com",
"070122dasdad3183",
"smtp.gmail.com",
"465",
"true",
"true",
true,
"javax.net.ssl.SSLSocketFactory",
"false",
to,
cc,
bcc,
"Automation test Reports",
"Please find the reports attached.\n\n Regards\nWebMaster",
System.getProperty("user.dir")+"\\Reports.zip",
"Reports.zip");
}
public static boolean sendMail(String userName,
String passWord,
String host,
String port,
String starttls,
String auth,
boolean debug,
String socketFactoryClass,
String fallback,
String[] to,
String[] cc,
String[] bcc,
String subject,
String text,
String attachmentPath,
String attachmentName){
Properties props = new Properties();
//Properties props=System.getProperties();
props.put("mail.smtp.user", userName);
props.put("mail.smtp.host", host);
if(!"".equals(port))
props.put("mail.smtp.port", port);
if(!"".equals(starttls))
props.put("mail.smtp.starttls.enable",starttls);
props.put("mail.smtp.auth", auth);
// props.put("mail.smtps.auth", "true");
if(debug){
props.put("mail.smtp.debug", "true");
}else{
props.put("mail.smtp.debug", "false");
}
if(!"".equals(port))
props.put("mail.smtp.socketFactory.port", port);
if(!"".equals(socketFactoryClass))
props.put("mail.smtp.socketFactory.class",socketFactoryClass);
if(!"".equals(fallback))
props.put("mail.smtp.socketFactory.fallback", fallback);
try
{
//Session session = Session.getDefaultInstance(props, null);
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{ return new PasswordAuthentication("acv.ddg#gmail.com","070122sd3183"); }
});
session.setDebug(debug);
MimeMessage msg = new MimeMessage(session);
msg.setText(text);
msg.setSubject(subject);
//attachment start
// create the message part
Multipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
DataSource source =
new FileDataSource(attachmentPath);
messageBodyPart.setDataHandler(
new DataHandler(source));
messageBodyPart.setFileName(attachmentName);
multipart.addBodyPart(messageBodyPart);
// attachment ends
// Put parts in message
msg.setContent(multipart);
msg.setFrom(new InternetAddress(userName));
for(int i=0;i<to.length;i++){
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to[i]));
}
for(int i=0;i<cc.length;i++){
msg.addRecipient(Message.RecipientType.CC, new InternetAddress(cc[i]));
}
for(int i=0;i<bcc.length;i++){
msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc[i]));
}
msg.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(host, userName, passWord);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
return true;
}
catch (Exception mex)
{
mex.printStackTrace();
return false;
}
}
}
Please let us know will this code work or is there any better way of doing this?
Thanks,
Sudhansu
Your MimeMessage can either have text set via setText() or a multipart-body.
Since your use atteachments you have to use multipart. To add some plain text to the message create another MimeBodyPart and add it as the first to your Multipart:
....
Multipart multipart = new MimeMultipart();
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText(text);
mmp.addBodyPart(textPart);
MimeBodyPart messageBodyPart = new MimeBodyPart();
....
I'm trying to get Java mail to send bounced email to a different address than the sender's address and not send the bounce message to the sender at all.
So far I can't do either in a test program ( below ).
The sender is "joe#acme.com".
I want bounce messages to go and only go to "bounce#acme.com"
I'm trying setting both the reply-to address and the Return-Path: header, but the bounces do not go to bounce#acme.com, only to joe#acme.com
When looking at the header of the bounce message the Return-Path: header is getting set to the sender, joe#acme.com, not to bounce#acme.com the way I want it to be.
I'm using javamail 1.4
Thanks in advance for any help or tips
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import java.util.Properties;
public class SendEmail {
public static void main(String[] args) throws Exception{
String smtpServer = "msg.abc.acme.cp,";
int port = 25;
String userid = "authorized.person";
String password = "password";
String contentType = "text/html";
String subject = "test: bounce an email to a different address from the sender";
String from = "joe#acme.com";
String to = "bogus#fauxmail.com";
String replyto = "bounce#acme.com";
String body = "Test: get message to bounce to a separate email address";
InternetAddress[] arrayReplyTo = new InternetAddress[1];
arrayReplyTo[0] = new InternetAddress(replyto);
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.host", smtpServer);
Session mailSession = Session.getInstance(props);
// Get runtime more runtime output when attempting to send an email
//mailSession.setDebug(true);
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from));
message.setReplyTo(arrayReplyTo);
message.setRecipients(Message.RecipientType.TO, to);
message.setSubject(subject);
message.setContent(body,contentType);
message.setHeader("Return-Path:","<bounce#acme.com>");
Transport transport = mailSession.getTransport();
try{
System.out.println("Sending ....");
transport.connect(smtpServer, port, userid, password);
transport.sendMessage(message,message.getRecipients(Message.RecipientType.TO));
System.out.println("Sending done ...");
}
catch(Exception e) {
System.err.println("Error Sending: ");
e.printStackTrace();
}
transport.close();
}// end function main()
}// end class SendEmail
You need to set the "envelope from" address. See the javadocs for the com.sun.mail.smtp package for the property you can use to set it, or use the SMTPMessage class to set it.
And then hope that the mail server bouncing the message does the right thing and follows the spec...
This stackoverflow post explains that you need to set the sender's from using MimeMessage.addFrom() and that you need to set the "mail.smtp.host"
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import java.util.Properties;
public class SendEmail {
public static void main(String[] args) throws Exception{
String smtpServer = "msg.abc.acme.cp,";
int port = 25;
String userid = "authorized.person";
String password = "password";
String contentType = "text/html";
String subject = "test: bounce an email to a different address from the sender";
String from = "joe#acme.com";
String to = "bogus#fauxmail.com";
String bounceAddr = "bounce#acme.com";
String body = "Test: get message to bounce to a separate email address";
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.host", smtpServer);
props.put("mail.smtp.from", bounceAddr);
Session mailSession = Session.getInstance(props);
// Get runtime more runtime output when attempting to send an email
//mailSession.setDebug(true);
MimeMessage message = new MimeMessage(mailSession);
//message.setFrom(new InternetAddress(from));
message.addFrom(InternetAddress.parse(from));
message.setRecipients(Message.RecipientType.TO, to);
message.setSubject(subject);
message.setContent(body,contentType);
Transport transport = mailSession.getTransport();
try{
System.out.println("Sending ....");
transport.connect(smtpServer, port, userid, password);
transport.sendMessage(message,message.getRecipients(Message.RecipientType.TO));
System.out.println("Sending done ...");
}
catch(Exception e) {
System.err.println("Error Sending: ");
e.printStackTrace();
}
transport.close();
}// end function main()
}// end class SendEmail
javax.mail.MessagingException: Could not convert socket to TLS;
nested exception is:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
my code:
public class SendMail implements ActionListener
{
public void actionPerformed(ActionEvent e1)
{
String TO = textTo.getText();
Component Mail=sendMail;
if((TO.trim().length() < 1))
{
JOptionPane.showMessageDialog(Mail,
"Please enter some address to send mail",
"No Address to send mail", JOptionPane.ERROR_MESSAGE);
}
else{
String host = "smtp.gmail.com";//host name
String from = "mymail#gmail.com";//sender id
String to = textTo.getText();//reciever id
String pass = "password";//sender's password
String fileAttachment = textAttFile.getText();//file name for attachment
//system properties
Properties prop = System.getProperties();
// Setup mail server properties
prop.put("mail.smtp.gmail", host);
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.smtp.host", host);
prop.put("mail.smtp.user", from);
prop.put("mail.smtp.password", pass);
prop.put("mail.smtp.port", "587");
prop.put("mail.smtp.auth", "true");
//session
Session session = Session.getInstance(prop, null);
// Define message
MimeMessage message = new MimeMessage(session);
try
{
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject(textSub.getText());
// create the message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
//message body
messageBodyPart.setText(body.getText());
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
//attachment
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(fileAttachment);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileAttachment);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
//send message to reciever
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
JOptionPane.showMessageDialog(sendMail,
"Mail Sent Successfully.",
"Mail Sent.", JOptionPane.INFORMATION_MESSAGE);
}
catch(Exception e)
{
System.out.println(e.toString());
}
}}
}
This JavaMail FAQ entry might help:
When connecting to my mail server over SSL I get an exception like "unable to find valid certification path to requested target".