I have a problem and need some help
In my program I need to send a mail and smtp server depends of one var,
if var is 1 then must send mail from a gmail address
or if var is 2 the mail is send from a diferent smtp server
I use TLS from both accounts and all is ok (if only send from 1 server)... but when I try to send from both servers (because my var change depend from 1 to 2, or 2 to 1 many times during the execution) I recieved always an error
Here my code:
public static void correo(String empresa, String[] dest, String archivo, String nom_arch){
String cuenta = "", asunto = "", pw = "", pto = "", server = "";
try
{
Properties props = new Properties();
if("1".equals(empresa)){
cuenta = "example#gmail.com";
asunto = "xxxxxxx";
pw = "password";
pto = "587";
server = "smtp.gmail.com";
}
else if ("2".equals(empresa)) {
cuenta = "example#server.com";
asunto = "yyyyyyy";
pw = "password";
pto = "25";
server = "smtpout.secureserver.net";
}
props.setProperty("mail.smtp.host", server);
props.setProperty("mail.smtp.port", pto);
props.setProperty("mail.smtp.user", cuenta);
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(props,null);
BodyPart texto = new MimeBodyPart();
texto.setText("Some Text");
BodyPart adjuntoPDF = new MimeBodyPart();
adjuntoPDF.setDataHandler(new DataHandler(new FileDataSource(archivo+".pdf")));
adjuntoPDF.setFileName(nom_arch+".pdf");
MimeMultipart multiparte = new MimeMultipart();
multiparte.addBodyPart(texto);
multiparte.addBodyPart(adjuntoPDF);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(cuenta));
InternetAddress[] direcciones = new InternetAddress[dest.length];
for(int i=0; i<dest.length; i++){
direcciones[i] = new InternetAddress(dest[i]);
}
message.addRecipients(Message.RecipientType.TO,direcciones);
message.setSubject(asunto);
message.setContent(multiparte);
Transport t = session.getTransport("smtp");
t.connect(cuenta, pw);
t.sendMessage(message, message.getAllRecipients());
t.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
See this JavaMail FAQ list of common JavaMail mistakes. Change Session.getDefaultInstance to Session.getInstance.
Related
Hello everyone i am trying to send an email using JavaMail and Amazon SES, this is the code I have written,
static Properties props = new Properties();
static {
props.setProperty("mail.transport.protocol", "aws");
props.setProperty("mail.aws.user", "userName");
props.setProperty("mail.aws.password", "secretKey");
}
void doThis() throws AddressException, MessagingException {
Session session = Session.getDefaultInstance(props);
Message mimeMessage = new MimeMessage(session);
mimeMessage.setFrom(new InternetAddress("support#xyz.com"));
mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse("kaustubh#xyz.com"));
mimeMessage.setSubject("Subject");
mimeMessage.setContent("Message contenet", "text/html");
Transport t = new AWSJavaMailTransport(session, null);
t.connect();
t.sendMessage(mimeMessage, null);
t.close();
}
but i am getting an exception saying,
Exception in thread "main" javax.mail.SendFailedException: Unable to send email;
nested exception is:
com.amazonaws.services.simpleemail.model.MessageRejectedException: Email address is not verified. The following identities failed the check in region US-EAST-1
And I am not getting any solution for this, any suggestions from the stackOverflow family would be a great help.
Here is V2 SES code that sends email...
public class SendMessage {
// This value is set as an input parameter
private static String SENDER = "";
// This value is set as an input parameter
private static String RECIPIENT = "";
// This value is set as an input parameter
private static String SUBJECT = "";
// The email body for recipients with non-HTML email clients
private static String BODY_TEXT = "Hello,\r\n" + "Here is a list of customers to contact.";
// The HTML body of the email
private static String BODY_HTML = "<html>" + "<head></head>" + "<body>" + "<h1>Hello!</h1>"
+ "<p>Here is a list of customers to contact.</p>" + "</body>" + "</html>";
public static void main(String[] args) throws IOException {
if (args.length < 3) {
System.out.println("Please specify a sender email address, a recipient email address, and a subject line");
System.exit(1);
}
// snippet-start:[ses.java2.sendmessage.main]
SENDER = args[0];
RECIPIENT = args[1];
SUBJECT = args[2];
try {
send();
} catch (IOException | MessagingException e) {
e.getStackTrace();
}
}
public static void send() throws AddressException, MessagingException, IOException {
Session session = Session.getDefaultInstance(new Properties());
// Create a new MimeMessage object
MimeMessage message = new MimeMessage(session);
// Add subject, from and to lines
message.setSubject(SUBJECT, "UTF-8");
message.setFrom(new InternetAddress(SENDER));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(RECIPIENT));
// Create a multipart/alternative child container
MimeMultipart msgBody = new MimeMultipart("alternative");
// Create a wrapper for the HTML and text parts
MimeBodyPart wrap = new MimeBodyPart();
// Define the text part
MimeBodyPart textPart = new MimeBodyPart();
textPart.setContent(BODY_TEXT, "text/plain; charset=UTF-8");
// Define the HTML part
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(BODY_HTML, "text/html; charset=UTF-8");
// Add the text and HTML parts to the child container
msgBody.addBodyPart(textPart);
msgBody.addBodyPart(htmlPart);
// Add the child container to the wrapper object
wrap.setContent(msgBody);
// Create a multipart/mixed parent container
MimeMultipart msg = new MimeMultipart("mixed");
// Add the parent container to the message
message.setContent(msg);
// Add the multipart/alternative part to the message
msg.addBodyPart(wrap);
try {
System.out.println("Attempting to send an email through Amazon SES " + "using the AWS SDK for Java...");
Region region = Region.US_WEST_2;
SesClient client = SesClient.builder().region(region).build();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
message.writeTo(outputStream);
ByteBuffer buf = ByteBuffer.wrap(outputStream.toByteArray());
byte[] arr = new byte[buf.remaining()];
buf.get(arr);
SdkBytes data = SdkBytes.fromByteArray(arr);
RawMessage rawMessage = RawMessage.builder()
.data(data)
.build();
SendRawEmailRequest rawEmailRequest = SendRawEmailRequest.builder()
.rawMessage(rawMessage)
.build();
client.sendRawEmail(rawEmailRequest);
} catch (SdkException e) {
e.getStackTrace();
}
// snippet-end:[ses.java2.sendmessage.main]
}
}
// snippet-end:[ses.java2.sendmessage.complete]
Exception in thread "main" javax.mail.SendFailedException: Unable to send email; nested exception is: com.amazonaws.services.simpleemail.model.MessageRejectedException: Email address is not verified. The following identities failed the check in region US-EAST-1
Amazon is telling you that you must verify the email address you're sending from or to. If the email address from and to are not verified the send email fails.
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