It's not the same without you

Join the community to find out what other Atlassian users are discussing, debating and creating.

Atlassian Community Hero Image Collage

Sending email using gmail smtp with groovy script fails

Tsol Jul 21, 2013

Hi everybody,

i'm using groovyrunner for sending an email without using the default JIRA smtp server.

I'm using the script as a post function in close workflow transition.

I have performed some tests and the script works fine when the host of my smtp mail server is Google Apps.

But when i use a custom smtp host my script doesn't work.

The script i use is the following

import javax.mail.internet.*;
import javax.mail.*
import javax.activation.*
import javax.mail.Multipart;
import javax.mail.internet.MimeMultipart;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.ComponentManager;
import com.atlassian.jira.issue.CustomFieldManager;
import com.atlassian.jira.issue.fields.CustomField;
import com.atlassian.jira.issue.comments.CommentManager;
import com.atlassian.jira.issue.attachment.Attachment;
import com.atlassian.jira.issue.history.ChangeItemBean;
import com.atlassian.jira.util.AttachmentUtils;
import groovy.text.GStringTemplateEngine;


//Get Comment Manager
CommentManager commentManager = componentManager.getCommentManager();

//Get custom field manager
CustomFieldManager customFieldManager = ComponentManager.getInstance().getCustomFieldManager();



//Get custom field email by id
CustomField customField_email = customFieldManager.getCustomFieldObject( 10205 );


//get value of customField_email
to = issue.getCustomFieldValue( customField_email )


//Email Headers
sender="test@gmail.com"
sendername="Test Test"

//Email acccount credentials
username="test@gmail.com"
password="test"


//Gmail Default port
port = 465

//Email Body
content = """\
<html>
<body>
<div>
test
</div>
</body>
</html>
"""

//Creat first part of email, Email Body


Multipart mp = new MimeMultipart("mixed");

MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(content.toString(), "text/html");
mp.addBodyPart(htmlPart);




//Email Properties

props = new Properties()
props.put("mail.smtp.port", port);
props.put("mail.smtp.socketFactory.fallback", "false");
props.put("mail.smtp.quitwait", "false");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");


//New session

Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(sender,sendername));
message.setSubject("${issue.getKey()}");
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setContent(mp)

try{
		Transport transport = session.getTransport("smtp");
		transport.connect( "smtp.gmail.com",port,username,password );
		transport.sendMessage(message,message.getAllRecipients());
		transport.close();
		log.warn ("mail sent sucesfully to : "+ issue.getCustomFieldValue( customField_email).toString())
		

}catch (MessagingException mex) {
         mex.printStackTrace();
}

When i choose the transition that scipt should executed i get no errors in logs but the following warning on screen

After that issue is like in no status. I have to reindex if i want to perform any workflow action on it.

Email is not sent.

Any idea what may cause the problem?

Cheers,

Kostas

3 answers

1 accepted

0 votes
Answer accepted
Tsol Jul 22, 2013

Finally it works. There is nothing to do with the default outgoing mail server.

I have changed the port and mail properties and i have restarted JIRA.

If i use the port "465" email is not sent. If i use port "25" works fine.

The script i'm using is the following:

import javax.mail.internet.*;
import javax.mail.*
import javax.activation.*
import javax.mail.Multipart;
import javax.mail.internet.MimeMultipart;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.ComponentManager;
import com.atlassian.jira.issue.CustomFieldManager;
import com.atlassian.jira.issue.fields.CustomField;
import com.atlassian.jira.issue.comments.CommentManager;
import com.atlassian.jira.issue.attachment.Attachment;
import com.atlassian.jira.issue.history.ChangeItemBean;
import com.atlassian.jira.util.AttachmentUtils;
import groovy.text.GStringTemplateEngine;


//Get Comment Manager
CommentManager commentManager = componentManager.getCommentManager();

//Get custom field manager
CustomFieldManager customFieldManager = ComponentManager.getInstance().getCustomFieldManager();


//Get custom field email by id
CustomField customField_email = customFieldManager.getCustomFieldObject( 10205 );


//get value of customField_email
to = issue.getCustomFieldValue( customField_email )


//Email Headers
sender="test@gmail.com"
sendername="Test Test"


//Email acccount credentials
username="test@gmail.com"
password="password"

//Gmail Default port
port = 25

//Email Body
content = """\
<html>
<body>
<div>
test
</div>
</body>
</html>
"""

//Creat first part of email, Email Body


Multipart mp = new MimeMultipart("mixed");

MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(content.toString(), "text/html");
mp.addBodyPart(htmlPart);




//Create attachment list

List attachmentIds = []


//Get change items during transition
List changeItems = transientVars["changeItems"]



//Get attachements
changeItems.each {ChangeItemBean cib ->
                        if (cib.getField() == "Attachment" && cib.getTo()) {
                            attachmentIds.add(cib.getTo())
                        }
}


//Create attachments email part
attachmentIds.each {attachmentId ->
                Attachment attachment = issue.attachments.find {Attachment attachment ->
                    attachment.id == new Long(attachmentId)
					
                }
				
				//File attFile = AttachmentUtils.getAttachmentFile(attachment)
				File attFile = AttachmentUtils.getAttachmentFile(attachment)
				
				
				
                //Create Second Part of Email, Attachments
				MimeBodyPart attPart = new MimeBodyPart()
                FileDataSource attFds = new FileDataSource(attFile)
                attPart.setDataHandler(new DataHandler(attFds))
                attPart.setFileName(attachment.filename)
                
				//log.debug("Attaching ${attachment.filename} to mail")
                mp.addBodyPart(attPart)
				log.warn ("Attaching ${attachment.filename} to mail")
}


//Email Properties

props = new Properties()
props.put("mail.smtp.port", port);
props.put("mail.smtp.socketFactory.fallback", "false");
props.put("mail.smtp.quitwait", "false");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");


//New session
Session session = Session.getInstance(props,
		  new javax.mail.Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, password);
			}
		  });
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(sender,sendername));
message.setSubject("${issue.getKey()}");
//message.setContent(content.toString(), "text/html");
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setContent(mp)

try{
		Transport transport = session.getTransport("smtp");
		transport.connect( "smtp.gmail.com",port,username,password );
		transport.sendMessage(message,message.getAllRecipients());
		transport.close();
		log.warn ("mail sent sucesfully to : "+ issue.getCustomFieldValue( customField_email).toString())

}catch (MessagingException mex) {
         mex.printStackTrace();
}

Jason Plumhoff Aug 05, 2013

Hi Kostas - is there any chance I could get you to post your pom file? I'm having trouble getting a script to run that uses external dependencies. I suspect I'm doing something silly and I would like a basis for comparison. If you could share any information about any files beyond the script (and where you put them) that would be greatly appreciated as well.

Thanks!

Tsol Aug 05, 2013

Hey Jason,

to be honest i haven't used any other dependencies apart from the ones by default included in JIRA and in scriptrunner.

Just saw your question that you have problem with dependencies. From some tests i have done with rest i had the same problems.

I have used the following in my script for getting results from a rest call

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

it seems to work. I didn't have the time to test it a lot but you can give it a try.

Hope this helps.

Cheers

0 votes
JamieA Jul 22, 2013

The script above seems to use gmail, but you're saying that does work? And it only does not work when using some other smtp server?

Anyway, there must be something in the logs. Your .printStackTrace will print the stack trace to the console, which might go to catalina.out or something.

Use
log.error ("some error", ex)

to make it go to the jira logs.

Could well be that you need to import the smtp server SSL cert or something... the logs will tell you.

Tsol Jul 22, 2013

Thanx for the help.

Cheers

0 votes
rajesh chilukuri Feb 13, 2019

how exactly do i need to write this java code? i mean in which file and where it should it be present related to Jenkinsfile ?

Suggest an answer

Log in or Sign up to answer
This widget could not be displayed.
This widget could not be displayed.
Community showcase
Published in Jira Software

Early Access: If you use Jenkins and Jira Software Cloud, you need to read this!

The Jira Software Cloud Team has been busy working on a simple, secure, and reliable way to integrate your build and deployment information from Jenkins with Jira Software Cloud. This means you don’t...

279 views 0 8
Read article

Community Events

Connect with like-minded Atlassian users at free events near you!

Find an event

Connect with like-minded Atlassian users at free events near you!

Unfortunately there are no Community Events near you at the moment.

Host an event

You're one step closer to meeting fellow Atlassian users at your local event. Learn more about Community Events

Events near you