How to send email with attachment in jenkinsfile - jenkins

I want to send email after post build action in jenkins. Hence I have write jenkinsfile as follows. But i want to send mail with pdf attachment.
Note: Please don't suggest email plugin procedure & configuration. I preferred Jenkins file method configuration
post {
success {
script {
echo "Success!! e-mailing scan results url to ${emailRecipients}"
mail(from: emailFrom, subject: emailSubjectCDSuccess + COMMIT, to: emailRecipients, body: emailBodyCheckmarx)
}
}
failure {
script {
echo "Failure :( !! e-mailing scan results url to ${emailRecipients}"
mail(from: emailFrom, subject: emailSubjectCDFailure, to: emailRecipients, body: emailBodyCD)
}
}
}

Instead of the default Email step, use the Email Extension Plugin, which allows you to add attachments.
emailext(
subject: "SUBJECT",
attachLog: true, attachmentsPattern: "**/*.txt",compressLog: true,
body: "Test Email" ,to: adress#g.com)

not an answer
try approximately the following parameters of mail step:
def boundary = '----------12345'
def attachment = 'hello world'.bytes.encodeBase64() //read bytes from file and encode as base64
def body = 'hello body'.getBytes('UTF-8').encodeBase64()
mail(
...
mimeType: "multipart/mixed; boundary=${boundary}",
//you can't add extra-spaces or drop empty lines in following string
body: """
${boundary}
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: base64
${body}
${boundary}
Content-Type: application/octet-stream; name="my-attachment.txt"
Content-Disposition: attachment
Content-Transfer-Encoding: base64
${attachment}
${boundary}--
""".trim()
)

Related

How to post parameters from angular to rails server

I am fairly new to angular and i am trying to send a name and image file to my server which is written in rails. But the data i am being received on my server is not correct and i have tried many fixes but nothing seems to be working. The request payload that being sent is this
-----WebKitFormBoundaryhRvQy5dRArcb6BfP
Content-Disposition: form-data; name="project[logo]"; filename="badge.png"
Content-Type: image/png
------WebKitFormBoundaryhRvQy5dRArcb6BfP
Content-Disposition: form-data; name="project[name]"
abc
------WebKitFormBoundaryhRvQy5dRArcb6BfP--
This is not being accepted in rails server and returns me a bunch of gibberish in the console/log
��2˾F
2ƺx���;p}}�0���'�C�F
��b7�Ӡ�}��c��Ii���W8��I#�<dy���}4�|���{c��5�iV�#�����*�����'��
:ظ׻�<+�I5��^��ԓk�qi���R91R��pi7QZϢ�����V�m��� �(��8�m�c%OGN#�k��k2�>_O�����^Ya��+�����1������^�����K�3�07q���{7�ܶ0+��&sZ�򽽴���w7�>f�^��A�/����d�����g�i�
PG?_��u�����5�i2��F$��\7(�ԟ�t8e9�3�9=Lk�#��ֽ��3��%FJ�QjI����f���qmI4֍4�^��P|�S���)Ԋ0Җ�AEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPE�����͊O6c��>y?횜����5�Z��Nuf��qr}ݶK�N�K�k̨BU'E^Ri/�W���G/�C�W?f��
RT������ׯ!�8a\�z�_^���Z�ݺEm�(��|��GJ�iS�8�k�{��ۻ��#��+"(��(�`��+��(��(��(��$��"��
2:�V��G��j���K`�S�LI���s�C�����+�����-h)[��q�
��/�^洫T��NMw[�^�z?]���%��ki
z�ͭ��f+��T��a���� S��H:��dz���{2���5
���A#���qڇ��t�D�D2LGz�q��`��nM|�/)�B�z���K��^p__�
���
This is my service.ts
postCreateProject(logo, name)
{
const formData: FormData = new FormData();
const url = EndPoints.BASE_URL + EndPoints.Projects;
formData.append('project[logo]', logo);
formData.append('project[name]', name)
console.log(formData.get('project[logo]'))
return this.httpService.postFileUpload(url, formData);
This is my postFileUpload in the httpService
postFileUpload(url: string, fmd: FormData): Observable<any> {
console.log('post file upload')
const headers = new HttpHeaders();
headers.append('Form-Data','FileUpload');
// headers.set('Content-Type', 'multipart/form-data');
// headers.set('Accept', 'application/json');
return this.http.post(url, fmd, {headers : headers});
}
If you need additional files please ask. Thanks for helping.
If you're using rails 5+ and angular 4+, you might try excluding the headers and just having
return this.http.post(url, fmd).
That's what I do (rails 6 with angular 10) and the data on the rails end is correct.

Uploading txt file via POST request with HttpBuilder

I want to upload a txt file to a website using a POST request with HTTPBuilder and multipart/form-data
I've tried running my function and I get a HTTP 200 OK response, but the file doesn't appear on the website anywhere.
private Map fileUpload(String url, File file){
log.debug "doPost: $url body: ${file.getName()}"
FileBody fileBody = new FileBody(file,ContentType.APPLICATION_OCTET_STREAM)
def result = [:]
try {
def authSite = new HTTPBuilder(url)
authSite.auth.basic(user, password)
authSite.request(POST) { req ->
headers.Accept = "application/json, text/javascript, */*; q=0.01"
req.params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000)
req.params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000)
def mpe = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE)
mpe.addPart("gxt",fileBody)
req.setEntity(mpe)
response.success = { resp, reader ->
result = reader
}
response.failure = { resp, reader ->
println "My response handler got response: ${resp.statusLine}"
}
}
}
catch (e) {
log.debug("Could not perform POST request on URL $url", e)
throw e
}
return result
}
From debugging this is the status recieved
3695 [main] DEBUG org.apache.http.wire - << "HTTP/1.1 200 OK[\r][\n]"
3695 [main] DEBUG org.apache.http.wire - << "Date: Thu, 10 Jan 2019 07:34:06 GMT[\r][\n]"
Anything I'm doing wrong? I don't get any errors but it just seems like nothing happens.
I don't have anything conclusive, but I suspect there is something invalid with the way you set up the multipart upload.
To help figure this out, below is a standalone, working, multipart upload groovy script using HttpBuilder:
#Grab('org.codehaus.groovy.modules.http-builder:http-builder:0.7.1')
#Grab('org.apache.httpcomponents:httpmime:4.2.1')
import org.apache.http.entity.mime.content.*
import org.apache.http.entity.mime.*
import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.Method.POST
fileUpload('https://httpbin.org/post', new File('data.txt'))
Map fileUpload(String url, File file){
println "doPost: $url body: ${file.name}"
def result
try {
new HTTPBuilder(url).request(POST) { req ->
requestContentType = "multipart/form-data"
def content = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE)
content.addPart(file.name, new InputStreamBody(file.newInputStream(), file.name))
req.entity = content
// json might be something else (like a reader)
// depending on the response content type
response.success = { resp, json ->
result = json
println "RESP: ${resp.statusLine}, RESULT: $json"
}
response.failure = { resp, json ->
println "My response handler got response: ${resp.statusLine}"
}
}
} catch (e) {
println "Could not perform POST request on URL $url"
throw e
}
result
}
The script assumes a file data.txt with the data to post in the current directory. The script posts to httpbin.org as a working test endpoint, adjust accordingly to post to your endpoint instead.
Saving the above in test.groovy and executing will yield something like:
~> groovy test.groovy
doPost: https://httpbin.org/post body: data.txt
RESP: HTTP/1.1 200 OK, RESULT: [args:[:], data:, files:[data.txt:{ "foo": "bar" }], form:[:], headers:[Accept:*/*, Connection:close, Content-Type:multipart/form-data; boundary=ZVZuV5HAdPOt2Sv7ZjxuUHjd8sDAzCz9VkTqpJYP, Host:httpbin.org, Transfer-Encoding:chunked], json:null, origin:80.252.172.140, url:https://httpbin.org/post]
(note that first run will take a while as groovy grapes need to download the http-builder dependency tree)
perhaps starting with this working example and working your way back to your code would help you pinpoint whatever is not working in your code.

imap disposition is null for attachment

In our application we are reading the emails from Gmail using iMap and saving in DB, In email there are two attachments (one is pdf file and other is digital signature file). For first file (pdf) I am getting disposition null and not able to process the attachment but for second file (p7s) getting right disposition value as attachment.
Following is header information of attachments:
------=_NextPart_001_0025_01D03944.5B3A2140
Content-Type: application/pdf;
name="USXMS III Draft PUS - VOPR # 15-814.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename="USXMS III Draft PUS - VOPR # 15-814.pdf"
------=_NextPart_000_0024_01D03944.5B3A2140
Content-Type: application/pkcs7-signature; name="smime.p7s"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="smime.p7s"
Following is relevant code to process the attachments of email:
//Process attchements of email
protected processAttachments(def workItem, def message) {
int attachmentCount = 0
def content = message.content
if (content instanceof Multipart) {
for (cntr in 0..(content.count - 1)) {
def bodyPart = content.getBodyPart(cntr)
def disposition = bodyPart.getDisposition()
println("Disposition is " + disposition + ".");// returns null for pdf
if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
if (this.saveAttachments(workItem, bodyPart)) {
attachmentCount++
}
}
}
}
return attachmentCount
}
So in above code getDisposition returns null for pdf file. Please let me know if you need more information.
Issue resolved as it was nested content. In case of disposition is null I have to loop through the content to find attachment(s).

Creating ICal with plugin, only seems to download, can't figure how to attach to send mail function

Standard Grails Mail Plugin Mail-Plugin
ICal Plugin for creating ICal files I-Cal-Plugin
I've used mail successfully with great ease, attatching files etc, however, getting Ical to work with the attachBytes from mail plugin is proving difficult
sendMail {
multipart true
to test#test.com
subject "whatever..."
html g.render(template:"/emails/Attendees", model:[ instance: inst])
inline "banner", "image/jpeg", new File("./web-app/images/emailTemplates/email_banner.png")
inline "footer", "image/jpeg", new File("./web-app/images/emailTemplates/lEdvn.png")
}
To attach files you use attachBytes which I was trying to use the standard example render function found on the example of the ical docs
def ical = render(contentType: 'text/calendar', filename: '<optional filename>') {
calendar {
events {
event(start: Date.parse('dd.MM.yyyy HH:mm', '31.10.2009 14:00'),
end: Date.parse('dd.MM.yyyy HH:mm', '31.10.2009 15:00'),
description: 'Events description',
summary: 'Short info1') {
organizer(name: 'Silvio Wangler', email: 'a#b.com')
}
}
}
}
The def ical technically doesn't matter still renders i.e. immediately downloads upon reaching this code block. The idea is to save and attach to the email, no download.
Thanks for your time
Anyone that stumbles across this post this is the answer:
def builder = new ICalendarBuilder()
builder.calendar {
events {
event(start: new Date(), end: (new Date()).next(), summary: 'Text') {
organizer(name:'Silvio', email:'test#test.com')
reminder(minutesBefore: 15, description: 'Alarm 123')
}
}
}
Then for the email sendMail function add:
attachBytes "appointment.ics", "text/calendar", builder.cal.toString().getBytes('UTF-8')

Groovy Httpbuilder authentication with Realm + RABBIT MQ

I am trying to to make a rabbitmq http api call to know how queues are there and other infos...
I need 3 variables to pass on to the api
1) url: (http://localhost:55672/api) 2) username/password: guest/guest
3) realm: "RabbitMQ Management" //i am not sure if this is important
4) path: "/queues"
when i make curl statement it gives a positive response
sudo curl -i -u guest:guest (http://localhost:55672)/api/queues
HTTP/1.1 200 OK
Server: MochiWeb/1.1 WebMachine/1.7 (participate in the frantic)
Date: Tue, 03 Jul 2012 01:39:05 GMT
Content-Type: application/json
Content-Length: 6176
Cache-Control: no-cache
but using httpbuilder from groovy. here is the code
def http = new HTTPBuilder("(http://localhost:55672/api)")
http.auth.basic 'guest','guest'
http.request(GET) { req ->
uri.path = '/queues'
response.success = { resp, reader ->
assert resp.statusLine.statusCode == 200
println "Got response: ${resp.statusLine}"
println "Content-Type: ${resp.headers.'Content-Type'}"
println reader.json
}
response.'404' = { println 'Not found' }
}
I am getting "not found" as the result. I am not including realm because I am unable to if i can insert "realm" in httpbuilder. it only comes with OAuth however I need to use basic auth for rabbit mq http api calls.
Does anyone knows how to include realm name in httpbuilder groovy for basic authentication? is there any other way. Kindly let me know! thanks!
Does this work?
def http = new HTTPBuilder( 'http://localhost:55672' )
http.auth.basic 'guest','guest'
http.request(GET) { req ->
uri.path = '/api/queues'
response.success = { resp, reader ->
assert resp.statusLine.statusCode == 200
println "Got response: ${resp.statusLine}"
println "Content-Type: ${resp.headers.'Content-Type'}"
println reader.json
}
response.'404' = { println 'Not found' }
}
Took the braces and the path out of your base url, added /api to the path

Resources